8

I wish to define classes that will produce the following xml using System.Xml.Serialization.XmlSerializer. I am struggling to get the items list, with attributes that does not contain a child 'container' element for 'item' elements.

<?xml version="1.0" ?>
<myroot>
   <items attr1="hello" attr2="world">
      <item id="1" />
      <item id="2" />
      <item id="3" />
   </items>
</myroot>
abatishchev
  • 98,240
  • 88
  • 296
  • 433
Sprintstar
  • 7,938
  • 5
  • 38
  • 51

1 Answers1

18

with XmlSerializer things are either lists or they have members. To do that you need:

[XmlRoot("myroot")]
public class MyRoot {
    [XmlElement("items")]
    public MyListWrapper Items {get;set;}
}

public class MyListWrapper {
    [XmlAttribute("attr1")]
    public string Attribute1 {get;set;}
    [XmlAttribute("attr2")]
    public string Attribute2 {get;set;}
    [XmlElement("item")]
    public List<MyItem> Items {get;set;}
}
public class MyItem {
    [XmlAttribute("id")]
    public int Id {get;set;}
}

with example:

var ser = new XmlSerializer(typeof(MyRoot));
var obj = new MyRoot
{
    Items = new MyListWrapper
    {
        Attribute1 = "hello",
        Attribute2 = "world",
        Items = new List<MyItem>
        {
            new MyItem { Id = 1},
            new MyItem { Id = 2},
            new MyItem { Id = 3}
        }
    }
};
ser.Serialize(Console.Out, obj);

which generates:

<myroot xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://
www.w3.org/2001/XMLSchema">
  <items attr1="hello" attr2="world">
    <item id="1" />
    <item id="2" />
    <item id="3" />
  </items>
</myroot>

you can remove the xsi/xsd namespace aliases if you want, of course.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • Wow, awesome work Marc. It was marking the 'Items' collection in the wrapper as simply XmlElement, rather than XmlArrayItem which I was missing. Thank you so much! – Sprintstar Jun 28 '11 at 08:55
  • Thanks for the answer but child members for me aren't being populated when there's only one within the xml. Any ideas why? Thanks :) – Gareth Nov 10 '18 at 03:30
  • @Gareth almost certainly "yes, I can help with that", but it would really really help if you could show me the XML and the class(es) you're trying to use with it. – Marc Gravell Nov 10 '18 at 09:45