Rich
Rich

Reputation: 87

Xml Serialization of a List where the parent element has additional elements

How would this be achieved in C# xml serializable class(s)?

<Category Attrib1="Value1" Attrib2="Value2">
  <Item>Item1</Item>
  <Item>Item2</Item>
  <Item>Item3</Item>
  <Item>Item4</Item>
</Category>

Inheriting Category from List<Item> results in the two Category properties being ignored by the xml serializer. If Category is composed of a List<Item> property a parent element is added around all the Item's (e.g. Category\Items\Item). Both are undesirable. The Xml must look like the example above.

Upvotes: 3

Views: 1864

Answers (1)

Wim
Wim

Reputation: 12082

Try this:

public class Category
{       
    [XmlAttribute]
    public string Attrib1 { get; set; }

    [XmlAttribute]
    public string Attrib2 { get; set; }     

    [XmlElement("Item")]
    public List<string> Items { get; set; }
}

Tested and works fine.

Upvotes: 3

Related Questions