我有以下课程:
[XmlRoot("testclass")]
public class TestClass
{
[XmlElement("name")]
public string Name { get; set; }
[XmlElement("value")]
public string Value { get; set; }
[XmlElement("items")]
public XmlDocument Items
{
get;
set;
}
}
现在使用以下数据初始化类:
XmlDocument xml = new XmlDocument();
xml.LoadXml(@"
<items>
<item>
<name>item1</name>
<value>value1</value>
</item>
<item>
<name>item2</name>
<value>value2</value>
</item>
</items>
");
TestClass tc = new TestClass() {
Name = "testclass",
Value = "testclassvalue",
Items = xml
};
当我序列化(.NET XmlSerializer)时,这个类我得到以下xml输出
<?xml version="1.0" encoding="utf-16"?>
<testclass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<name>testclass</name>
<value>testclassvalue</value>
<items>
<items>
<item>
<name>item1</name>
<value>value1</value>
</item>
<item>
<name>item2</name>
<value>value2</value>
</item>
</items>
</items>
</testclass>
让xmlserializer像这样输出节点的最佳方法是什么?
<?xml version="1.0" encoding="utf-16"?>
<testclass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<name>testclass</name>
<value>testclassvalue</value>
<items>
<item>
<name>item1</name>
<value>value1</value>
</item>
<item>
<name>item2</name>
<value>value2</value>
</item>
</items>
</testclass>
将xml序列化到我的班级的最佳方法是什么?因此,以节点开头的xmlelement将被反序列化回我的ItemsXml成员。
答案 0 :(得分:0)
尝试更改:
[XmlElement("items")]
public XmlDocument Items { get; set; }
只是:
// [XmlArray("items")] <--- you can add this to get a lowercase "items"
// [XmlArrayItem("item")] <--- and this to name the actual item
public XmlDocument Items { get; set; }
没有[XmlElement("items")]
。