我是 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
s在列表里面itens
标签。我该怎么做?
类(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; }
}
我正在使用这个进行序列化:
new XmlSerializer(typeof(List<Item>)).Serialize(Console.Out, list);
最佳答案
您需要另一个属性类型为 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
属性(property)作为Items
的内容元素而不是子元素 text
元素替换 [XmlElement("text")]
与 [XmlText]
:
[XmlText]
public string text { get; set; }
关于c# - 如何序列化列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31800196/