首页 > 解决方案 > 如何使用 XmlSerializer 反序列化未知元素?

问题描述

我有一些需要反序列化的 xml:

<MysteryXml niceAttribute="I know">
    <UnknownNode attr1="someValue" attr2="anotherValue"> <- this nodes attributes and children are unknows
        <Name>
            <Value />
            <AnotherValue />
        </Name>
        <CreatedBy>Unit Test</CreatedBy>
    </UnknownNode>
    <KnownNode nice="anotherAttr" />
</MysteryXml>

我有一个 C# 类来反序列化 xml

    [Serializable()]
    [DesignerCategory("code")]
    [XmlType(AnonymousType = true)]
    [XmlRoot(ElementName = "MysteryXml", IsNullable = false)]
    public class MysteryXml
    {
        [XmlElement] 
        // Here I have a node[] but I would like an XElement
        // If I set the type to XElement I only get the child node
        public object? UnknownNode { get; set; }

        [XmlElement]
        public KnownNode KnownNode { get; set; }

        [XmlAttribute]
        public string niceAttribute {get;set;}
    }

是否可以使用 XmlSerializer 将完整的 xml 作为字符串或 UnknownNode 的 XElement 获取?

谢谢

标签: c#xml

解决方案


推荐阅读