XML根据属性反序列化为类型

时间:2012-02-28 12:58:08

标签: c# xml deserialization

我有以下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#代码以正确反序列化? 通常我会做类似的事情:

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; }    
}

但是当元素名称相同但内容不同时,我不知道如何根据属性使用它。

2 个答案:

答案 0 :(得分:1)

使用基于标准属性的序列化无法做到这一点,您必须编写自己的代码来解析文档并相应地创建对象。

极其简化但有效的例子:

using System.Xml;

class A {
    public string Something { get; set; }
}
class B {
    public string SomethingDifferent { get; set; }
}

class Program {

    const string xml = @"
<values>
  <value type='A'>
    <something>ABC</something>
  </value>
  <value type='B'>
    <something-different>ABC</something-different>
  </value>
</values>
";

    static void Main(string[] args) {

        XmlDocument doc = new XmlDocument();
        doc.LoadXml(xml);

        foreach (XmlNode node in doc.SelectNodes("/values/value")) {
            string type = node.Attributes["type"].Value;
            switch (type) { 
            case "A":
                A a = new A();
                foreach (XmlNode propertyNode in node.ChildNodes) {
                    switch (propertyNode.Name) {
                    case "something":
                        a.Something = propertyNode.InnerText;
                        break;
                    }
                }
                break;
            case "B":
                // etc ...
                break;
            }
        }

    }
}

答案 1 :(得分:-2)

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

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