Serialize 0-n elements inside another element
I have two classes like this:
public class Product
{
public string Name { get; set; }
public int Id { get; set; }
}
public class Category
{
public string CategoryName { get; set; }
public List<Product> Products { get开发者_C百科; set; }
}
Is there some way I can decorate my Products property on the Category class, so it is serialized like this?
<Container>
<Category>
<CategoryName>Unicorn Stuff</CategoryName>
<Product>
<Id>1212</Id>
<Name>Unicorn Dust</Name>
</Product>
<Product>
<Id>1829</Id>
<Name>Horn Extension</Name>
</Product>
<Product>
<Id>27373</Id>
<Name>Facemask with hole</Name>
</Product>
</Category>
<Category>
<CategoryName>Pixie</CategoryName>
<Product>
<Id>222</Id>
<Name>Pixie Dust</Name>
</Product>
</Category>
</Container>
Note that Each category has category elements (Category name) AND 0-n Product child elements.
...Or do I have to drop down to generating the document in a more manual way?
(This is not how I would have designed the xml structure, but hey - we live in an imperfect world)
Place the [XmlElement]
attribute on the list:
public class Category
{
public string CategoryName { get; set; }
[XmlElement]
public List<Product> Products { get; set; }
}
I believe XSD.exe can create the XSD from your class for you. Then you would simply use the basic XmlSerializer to serialize to your XSD.
Alternatively, you can create your XSD, and generate your class from the XSD. Either way should work.
精彩评论