XML根据属性反序列化为类型 [英] XML De-serialize into type based on attribute

查看:103
本文介绍了XML根据属性反序列化为类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下几段XML:

<values>
<value type="A">
<something>ABC</something>
<something-else>DEF</something-else>
</value>
<value type="B">
<something-different>ABC</something-different>
<something-complex>
<id>B</id>
<name>B</name>
</something-complex>
</value>

我将如何创建C#代码来反序列化?
通常我会做类似的事情:

How would I create the C# code to de-serialize this properly? Normally I'd do something like:

public class A
{
    [XmlElement("something")]
    public string Something { get; set; }
    [XmlElement("something-else")]
    public string SomethingElse { get; set; }    
}

public class B
{
    [XmlElement("something-different")]
    public string SomethingDifferent { get; set; }    
    [XmlElementAttribute("something-complex")]
    public B_ID SomethingComplex { get; set; }
}
public class B_ID
{
    [XmlElement("id")]
    public int ID { get; set; }
    [XmlElement("something-else")]
    public string Name { get; set; }    
}

但是我不知道如何在元素具有相同的名称但内容不同。

But I have no idea how to use this based on an attribute when the elements have the same name but different content.

推荐答案

经过深思熟虑,解决此问题的最简单方法是对数据进行快速文本替换以将XML转换为:

After a lot of thought, the easiest way to solve this, is to just do a quick text replace on the data to transform the XML into:

<values>
<value-a>
<something>ABC</something>
<something-else>DEF</something-else>
</value-a>
<value-b>
<something-different>ABC</something-different>
<something-complex>
<id>B</id>
<name>B</name>
</something-complex>
</value-b>

这篇关于XML根据属性反序列化为类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆