c# - xml反序列化时如何将子节点的内部xml作为字符串返回

标签 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>

我想在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/

相关文章:

c# - 是否可以从 XmlSerializer 序列化中排除某些类型的成员?

c++ - 使用 C++ 序列化对象的首选方法

c# - 在 C# 中创建 Notepad++ 插件

c# - 将 completeAdding 唤醒已经被 take 阻塞的线程

java - 调试 NullPointerException

c# - 如何检查xElement值是否存在?

c# - 如何使用 JSON.Net 将 System.Drawing.Size 反序列化/序列化为对象?

c# - 如何在不使用乘法(*)符号的情况下将十进制数相乘

c# - Blazor Server .NET 8 中的 Blazored.FluentValidation 问题

java - 使用 DocumentBuilderFactory 将 Xml 文档转换为 DOM 对象