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?
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
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.