XmlDocument成员的自定义(反)序列化

本文关键字:序列化 自定义 成员 XmlDocument | 更新日期: 2023-09-27 17:59:18

我有以下类:

[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序列化回我的类的最佳方式是什么?因此,以node开头的xmlelement将被反序列化回我的ItemsXml成员中。

XmlDocument成员的自定义(反)序列化

尝试更改:

[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")]