Serializing a class containing a custom class

Posted by Netfangled on Stack Overflow See other posts from Stack Overflow or by Netfangled
Published on 2012-09-30T21:35:56Z Indexed on 2012/09/30 21:37 UTC
Read the original article Hit count: 175

Filed under:
|
|

I want to serialize an object as xml that contains other custom classes. From what I understand (I've been reading MSDN and SO mostly), the XmlSerializer doesn't take this into account.

This is the line that's confusing me:

XML serialization serializes only the public fields and property values of an object into an XML stream. XML serialization does not include type information. For example, if you have a Book object that exists in the Library namespace, there is no guarantee that it will be deserialized into an object of the same type.

Taken from MSDN, here

For example, I want to serialize an object of type Order, but it contains a list of Products, and each one contains an object of type Category:

class Order
{
    List<Product> products;
}

class Product
{
    Category type;
}

class Category
{
    string name;
    string description;
}

And I want my Order object to be serialized like so:

<Order>
    <Product>
        <Category Name="">
            <Description></Description>
        </Category>
    </Product>
    <Product>
        <Category Name="">
            <Description></Description>
        </Category>
    </Product>
<Order>

Does the XmlSerializer already do this? If not, is there another class that does or do I have to define the serialization process myself?

© Stack Overflow or respective owner

Related posts about c#

Related posts about Xml