Netfangled
Netfangled

Reputation: 2081

Serializing a class containing a custom class

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?

Upvotes: 2

Views: 1823

Answers (1)

Wim Ombelets
Wim Ombelets

Reputation: 5265

An Order can be seen as a list of Products, a Product as a list of Categories (because it can pertain to multiple categories).

You can try using

//...
using System.Xml;
using System.Xml.Serialization;
//...

[XmlRoot("Order")]
public class Order
{
    [XmlArrayItem(ElementName = "Product", Type = typeof(Product))]
    public List<Product> Products;
}

public class Product
{
    [XmlArrayItem(ElementName = "Category", Type = typeof(Category))]
    public List<Category> Categories;
}

public class Category
{
    [XmlAttribute("Name")]
    public string name;

    [XmlElement("Description")]
    public string description;
}

The only trade-off is, that the <Products> and <Categories> (plural) tags will be visible, because the variables are named that way, but from a point of view of parsing the XML afterwards, that's not an issue. If any other fields show up in your XML that you don't want, you can have [XmlIgnore()] precede them.

Upvotes: 1

Related Questions