【问题标题】:How to Deserialize XML elements to generic list with unknown element names如何将 XML 元素反序列化为具有未知元素名称的通用列表
【发布时间】:2014-04-30 09:26:41
【问题描述】:

我正在从数据库表列中检索并成功反序列化已知元素名称的 xml 字符串(这些名称不会更改),但也有一些称为“其他属性”的嵌套 XML 元素并不总是已知的。我在将这些未知元素名称反序列化为通用列表时遇到了一些麻烦,因此我可以在反序列化后将它们显示在 html 中。

XML如下:

<Detail>
<DetailAttributes>
<Name>Name_123</Name>
<Type>Type_123</Type>
</DetailAttributes>
<OtherAttributes>
<SummaryKey AttributeName="SummaryKey">SummaryKey_123</SummaryKey>
<Account AttributeName="Account">Account_123</Account>
</OtherAttributes>
</Detail>

反序列化“名称”和“类型”元素没有问题,我可以反序列化“SummaryKey”和“帐户”元素,但前提是我明确指定它们的元素名称 - 这不是所需的方法,因为“OtherAttributes” ' 可能会发生变化。

我的课程如下:

[XmlRoot("Detail")]
public class objectDetailsList
{
    [XmlElement("DetailAttributes"), Type = typeof(DetailAttribute))]
    public DetailAttribute[] detailAttributes { get; set; }

    [XmlElement("OtherAttributes")]
    public List<OtherAttribute> otherAttributes { get; set; }

    public objectDetailsList()
    {
    }
}
[Serializable]
public class Detail Attribute
{
    [XmlElement("Type")]
    public string Type { get;set; }

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

    public DetailAttribute()
    {
    }
}

[Serializable]
public class OtherAttribute
{
    //The following will deserialise ok

    //[XmlElement("SummaryKey")]
    //public string sumKey { get; set; }

    //[XmlElement("Account")]
    //public string acc { get; set; }

    //What I want to do below is create a list of all 'other attributes' without known names

    [XmlArray("OtherAttributes")]
    public List<Element> element { get; set; }
}

[XmlRoot("OtherAttributes")]
public class Element
{
    [XmlAttribute("AttributeName")]
    public string aName { get; set; }

    [XmlText]
    public string aValue { get; set; }
}

当我尝试检索 OtherAttribute 元素的反序列化列表时,计数为零,因此它无法访问嵌套在“其他属性”中的元素。

有人可以帮我解决这个问题吗?

【问题讨论】:

    标签: c# xml generics


    【解决方案1】:

    使用像这样的具体类和动态数据,您将无法依靠标准 XmlSerializer 来为您序列化/反序列化 - 因为它反映在您的类上,而您想要填充的属性根本不存在.如果您的“OtherAttributes”集合是已知且有限的,并且不会受到未来更改的影响,您可以为一个类提供所有可能的属性,但这会给您一个丑陋的臃肿类(我认为您已经决定这不是解决方案)。

    因此的实际选择:

    • 手动操作。使用 XmlDocument 类,使用 .Load() 加载数据,并使用 XPath 查询(类似于“/Detail/OtherAttributes/*”)使用 .SelectNodes() 迭代节点。您必须自己编写很多内容,但这使您可以完全控制序列化/反序列化。您也不必在(可以说是多余的!)属性中覆盖您的代码。

    • 使用 Json.NET (http://james.newtonking.com/json),它可以更好地控制序列化和反序列化。它速度很快,有很好的文档,而且整体非常漂亮。

    【讨论】:

    • 我最初走的是 xsd.exe 路线,但实际上无济于事。所以我按照你的建议选择了 XmlDocument 类,它很有效 - 非常感谢!
    猜你喜欢
    • 2020-01-14
    • 2015-04-13
    • 1970-01-01
    • 1970-01-01
    • 2016-02-04
    • 1970-01-01
    • 2016-09-12
    • 1970-01-01
    • 2015-09-24
    相关资源
    最近更新 更多