xml反序列化期间如何将子节点的内部xml作为字符串返回

ear*_*ing 4 c# xml serialization deserialization

我正在反序列化大型xml文档。在大多数情况下,这很好。我不关心树后面的一些子节点,但是它们确实包含我想捕获以供以后使用的数据,但是我不想完全反序列化这些子节点。我宁愿使用整个节点并将其存储为字符串,以后再返回。

例如,给下面的xml文档:

<item>
    <name>item name</name>
    <description>some text</description>
    <categories>
        <category>cat 1</category>
        <category<cat 2</category>
    </categories>
    <children>
        <child>
            <description>child description</description>
            <origin>place of origin</origin>
            <other>
                <stuff>some stuff to know</stuff>
                <things>I like things</things>
            </other>
        </child>
     </children>
</item>
Run Code Online (Sandbox Code Playgroud)

我想读取另一个节点,并将内部xml存储为字符串(即“ <stuff>一些要了解的东西</ stuff> <things>我喜欢的东西</ things>”)。说得通?

在我的item课,我已经试过各种的System.Xml.Serialization对其他财产的属性,没有运气,如XmlTextXmlElement

我该如何完成?看来这将是一项相当普通的任务。

Cha*_*ger 5

您可以通过使用来反序列化为类型的对象XmlElement来实现XmlAnyElementAttribute

因此,作为示例,这些类将起作用:

[XmlRoot("item")]
public class Item
{
    [XmlElement("name")]
    public string Name { get; set; }

    [XmlElement("description")]
    public string Description { get; set; }

    [XmlArray("categories")]
    [XmlArrayItem("category")]
    public List<string> Categories { get; set; }

    [XmlArray("children")]
    [XmlArrayItem("child")]
    public List<Child> Children { get; set; }
}

public class Child
{
    [XmlElement("description")]
    public string Description { get; set; }

    [XmlElement("origin")]
    public string Origin { get; set; }

    [XmlAnyElement("other")]
    public XmlElement Other { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

如果需要内容的字符串值,则可以读取InnerXml属性。请参阅此小提琴以获得有效的演示。