1

When i try to serialize a class element of type Test, it gives an xml with root element as "testing" which is set using XmlRoot.

But when I try to serialize an element of class Elems, Test element is serialized with root element "Test" instead of "testing".

[XmlRoot("testing")]
public class Test
{
}

public class Elems
{
   public List<Test> how = new List<Test>();

    public Elems()
    {
        how.Add(new Test());
        how.Add(new Test());
        how.Add(new Test());
    }
}

This the Output when Elems is serialized,

<Elems xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" x
mlns:xsd="http://www.w3.org/2001/XMLSchema">
  <how>
    <Test />
    <Test />
    <Test />
  </how>
</Elems>

instead this is what i need.

<Elems xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" x
mlns:xsd="http://www.w3.org/2001/XMLSchema">
  <how>
    <testing />
    <testing />
    <testing />
  </how>
</Elems>

Thanks

Rozuur
  • 4,115
  • 25
  • 31

1 Answers1

3

Try like this:

public class Test { }

public class Elems
{
    public Elems()
    {
        How = new List<Test>();
        How.Add(new Test());
        How.Add(new Test());
        How.Add(new Test());
    }

    [XmlArray("how")]
    [XmlArrayItem("testing")]
    public List<Test> How { get; set; }
}

class Program
{
    static void Main()
    {
        var elems = new Elems();
        var serializer = new XmlSerializer(elems.GetType());
        serializer.Serialize(Console.Out, elems);
    }
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • This works,but why is XmlRoot decoration not working when used in List? – Rozuur Jan 08 '11 at 14:40
  • @Rozuur, XmlRoot applies only to the object you are serializing which in your case is Elems. Any other XmlRoot attributes on child properties are ignored. That's how it has been implemented. – Darin Dimitrov Jan 08 '11 at 14:50