0

Possible Duplicate:
How to rename <ArrayOf> XML attribute that generated after serializing List of objects

This should be really simple but I am missing something here. I need output xml in the below format when serializing my class.

<items>
 <item id="1" name="John">
 <item id="2" name="Peter">
 <item id="3" name="Shane">
<items>

Here is the class:

public class Item
    {
        [XmlAttribute]
        public string Id;
        [XmlAttribute]
        public string Name;
    }

Here is my test code:

var items = new List<Item>();
            for (int i = 0; i < 4; i++)
            {
                var item = new Item();
                item.Id = i.ToString();
                item.Name = "Jeff" + " - " + i.ToString();
                items.Add(item);
            }
            Ser(items);

static void Ser(object o)
        {
            XmlSerializer x = new XmlSerializer(o.GetType());

            var xns = new XmlSerializerNamespaces();
            xns.Add(string.Empty, string.Empty);

            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            settings.OmitXmlDeclaration = true;
            XmlWriter writer = XmlWriter.Create(Console.Out, settings);

            x.Serialize(writer, o, xns);
            Console.WriteLine();
        }

Output I am getting is:

<ArrayOfItem>
  <Item Id="0" Name="Jeff - 0" />
  <Item Id="1" Name="Jeff - 1" />
  <Item Id="2" Name="Jeff - 2" />
  <Item Id="3" Name="Jeff - 3" />
</ArrayOfItem>

I want to replace "ArrayOfItem" with "Items". Also, why am I seeing "ArrayOf" appended? Thanks in advance.

Community
  • 1
  • 1
stech
  • 675
  • 2
  • 9
  • 22

2 Answers2

0

You are getting ArrayOfItem as you are getting type of List<Item> which is Array of type Item. This is standard when you de-serialize the xml de-serializer will make array of type Item. You can serialize individual Item for format like that but still it won't be same.

If you serialize individual item you'll get

  <Item Id="0" Name="Jeff - 0" />
  <Item Id="1" Name="Jeff - 1" />
  <Item Id="2" Name="Jeff - 2" />
  <Item Id="3" Name="Jeff - 3" />
Mayank
  • 8,777
  • 4
  • 35
  • 60
0

Why not use linq2Xml..It is simple and cool

XElement doc=new XElement("Items");

foreach(var item in items)
{
    doc.Add(
        new XElement("Item",
        new XAttribute("Id",item.Id),new XAttribute("Name",item.Name)
           )
    );
}

doc.ToString();//your xml

Output:

<items>
 <item id="1" name="John">
 <item id="2" name="Peter">
 <item id="3" name="Shane">
<items>
Anirudha
  • 32,393
  • 7
  • 68
  • 89