我是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="�)">
foo
</Item>
<Item corret="1" order=")">
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="�)">
<test>foo</test>
</Item>
<Item corret="1" order=")">
<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);
答案 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; }