Jack
Jack

Reputation: 16724

How do I serialize a list?

I'm new to XmlSerializer, I have a List<T> that I'd like to serialize like this:

    <?xml version="1.0" encoding="utf-16"?>
    <ArrayOfItem xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<itens>
     <Item corret="0" order="&#x0;)">
     foo
     </Item>
     <Item corret="1" order="&#x1;)">
     baa
     </Item>
</itens>
    </ArrayOfItem>

instead of this (current output):

<?xml version="1.0" encoding="utf-16"?>
<ArrayOfItem xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
 <Item corret="0" order="&#x0;)">
 <test>foo</test>
 </Item>
 <Item corret="1" order="&#x1;)">
 <test>baa</test>
 </Item>
</ArrayOfItem>

i.e, remove the test tag, move its contents to item and place all the items in the list inside the itens tag. How do I do this?

The class:

[Serializable]
public class Item
{
    [XmlIgnore]
    public int correctIndex { get; set; }
    [XmlIgnore]
    public int index { get; set; }

    [XmlAttribute("corret")]
    public string IsCorrect
    {
        get { return correctIndex == index ? "1" : "0"; }
        set { }
    }

    [XmlAttribute("order")]
    public string Order
    {
        get { return string.Format("{0})", ((char)index).ToString()); }
        set { }
    }

    [XmlElement("test")]
    public string text { get; set; }
}

I'm serializing using this:

new XmlSerializer(typeof(List<Item>)).Serialize(Console.Out, list);

Upvotes: 1

Views: 104

Answers (1)

MarcinJuraszek
MarcinJuraszek

Reputation: 125660

You need another class with property typed as List<Item>:

[Serializable]
public class Items
{
    [XmlArray("itens")]
    public List<Item> itens { get; set; }
}

and serialization code:

var list = new Items() { itens = new List<Item>() { new Item() { correctIndex = 10, index = 11, text = "asdasd" } } };
new XmlSerializer(typeof(Items)).Serialize(Console.Out, list);

To serialize text property as content of Items element instead of child text element replace [XmlElement("text")] with [XmlText]:

[XmlText]
public string text { get; set; }

Upvotes: 3

Related Questions