开发者

Customized (de)serializing of XmlDocument member

I have following class:

[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;
    }
}

Now the class is initialized with following data:

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
};

When I serialize (.NET XmlSerializer) this classI get following xml output

<?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>

What would be the best way to get xmlserializer to output node like this?

<?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>

Also what would the best way to serialize this xml ba开发者_JAVA百科ck to my class? So that xmlelement starting with node would be deserialized back into my ItemsXml member.


Try changing:

[XmlElement("items")]
public XmlDocument Items { get; set; }

To just:

// [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; }

So without the [XmlElement("items")].

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜