如何序列化列表?

时间:2015-08-04 03:32:20

标签: c# xml xml-serialization

我是XmlSerializer的新手,我有一个List<T>,我想像这样序列化:

    <?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>

而不是此(当前输出):

<?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>

即,删除test代码,将其内容移至item,并将所有item放入itens标记内的列表中。我该怎么做?

班级:

[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; }
}

我正在使用此序列化:

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

1 个答案:

答案 0 :(得分:3)

您需要另一个类型为List<Item>的类:

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

和序列化代码:

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

要将text属性序列化为Items元素而不是子text元素,请将[XmlElement("text")]替换为[XmlText]

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