【问题标题】:Customized (de)serializing of XmlDocument memberXmlDocument 成员的自定义(反)序列化
【发布时间】:2011-06-17 07:48:09
【问题描述】:

我有以下课程:

[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 成员。

【问题讨论】:

    标签: c# .net xml-serialization


    【解决方案1】:

    尝试改变:

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

    【讨论】:

    • 感谢您的回答,但没有帮助。删除 XmlElement("items") 只是将第一个元素更改为大写 。 XmlArrayAttribute 和 XmlArrayItemAttribute 只能指定给数组类型(数组和集合) - 抛出异常:对于非数组类型,您可以使用以下属性:XmlAttribute、XmlText、XmlElement 或 XmlAnyElement。
    • sorry... 没有集中注意力 --- 现在才注意到您使用 XmlDocument 作为类型。为什么您不能使用具有名称和值属性的名为 Item 的类?
    • 我提供了项目 xml 作为一个简单的例子(也许太简单了:))。在实际应用中,这个项目 xml 的结构要复杂得多。所以这个简单的类是行不通的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-10
    • 1970-01-01
    相关资源
    最近更新 更多