Xml Serializing a List in Which a Parent Has Additional Elements

How will 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 a category from List<Item>causes the two properties of the category to be ignored by the xml serializer. If the Category consists of a property List<Item>, a parent element is added throughout the Element (for example, the \ Items \ Item category). Both are undesirable. Xml should look like the one shown above.

+3
source share
1 answer

Try the following:

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

+3
source

Source: https://habr.com/ru/post/1728181/


All Articles