【问题标题】:How to return inner xml of child node as string during xml deserialization如何在xml反序列化期间将子节点的内部xml作为字符串返回
【发布时间】:2016-12-18 19:58:02
【问题描述】:

我正在反序列化大型 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>

我想在 other 节点中读取,并将内部 xml 存储为字符串(即“一些要知道的东西我喜欢的东西”)。有意义吗?

在我的item 课程中,我尝试了其他属性上的各种System.Xml.Serialization 属性,但没有成功,例如XmlTextXmlElement 等。

我该如何做到这一点?这似乎是一项相当普遍的任务。

【问题讨论】:

    标签: c# xml serialization deserialization


    【解决方案1】:

    您可以通过使用XmlAnyElementAttribute 反序列化为XmlElement 类型的对象来做到这一点。

    因此,例如,这些类可以工作:

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

    如果你想要内容的字符串值,你可以阅读InnerXml 属性。有关工作演示,请参阅 this fiddle

    【讨论】:

      【解决方案2】:

      如果您使用的是 XmlDocument 对象,您可以使用 Xpath 来查询不同的标签。查看here 了解更多细节,但是,使用您的示例:

      XmlNode node = root.SelectSingleNode("/child/other");
      Console.WriteLine(node.InnerXml);
      

      【讨论】:

      • 我正在使用 XmlSerializer 反序列化数千个这些对象,我认为将其更改为迭代解析文件并构建对象会导致严重的性能损失。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多