2

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; 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)

Kjensen
  • 12,447
  • 36
  • 109
  • 171

2 Answers2

5

Place the [XmlElement] attribute on the list:

public class Category
{
    public string CategoryName { get; set; }
    [XmlElement]
    public List<Product> Products { get; set; }
}
John Saunders
  • 160,644
  • 26
  • 247
  • 397
  • I can't f#cking believe I did not try this before asking. I already have like 50 XmlElement attributes in the real classes already. Great, thanks! :) – Kjensen Apr 26 '11 at 20:25
  • @Kjensen: glad that helped. Could you post an example of the original XML in your question? – John Saunders Apr 26 '11 at 22:30
0

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.

AllenG
  • 8,112
  • 29
  • 40
  • You can use tools such as http://www.xmlforasp.net/CodeBank/System_Xml_Schema/BuildSchema/BuildXMLSchema.aspx to create XSD if you don't have one. – Bala R Apr 26 '11 at 19:59