我正在处理大型 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 属性,但没有成功,例如 XmlText
, XmlElement
等
我该如何实现?这似乎是一项相当常见的任务。
最佳答案
您可以通过使用 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用于工作演示。
关于c# - xml反序列化时如何将子节点的内部xml作为字符串返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38907191/