XML反序列化:不同的XML架构映射到同一个C#类 [英] XML deserialize: different xml schema maps to the same C# class
问题描述
我的一个程序的工作是从一个XML文件中读取客户名单,并将其反序列化到C#类象下面这样:
One of the jobs of my program is to read customer list from a xml file and deserialize them into C# class like below:
<?xml version="1.0" encoding="utf-8"?>
<customers>
<customer>
<name>john</name>
<id>1</id>
</customer>
<customer>
<name>mike</name>
<id>2</id>
</customer>
</customers>
C#类:
C# class:
[XmlRoot("customers")]
public class CustomerList {
[XmlElement("customer")]
public Customer[] Customers { get; set; }
}
public class Customer {
[XmlElement("name")]
public String Name {get; set;}
[XmlElement("id")]
public String Id {get; set;}
}
但最近客户想要的标签名从<$ c修改$ C>< ID> 到<代码>
像下面这样:
<?xml version="1.0" encoding="utf-8"?>
<customers>
<customer>
<name>john</name>
<code>1</code>
</customer>
<customer>
<name>mike</name>
<code>2</code>
</customer>
</customers>
有关代码将具有相同的含义与以前的标签'身份证'的价值。而且,他们希望这种转变过程中的程序应该修正,因此认识到在一段时间内这两个标签。
The value for 'code' will have the same meaning with previous tag 'id'. And they want that during transition the program should be amended so it recognizes both tags for a period of time.
有没有简单的方法来实现这一目标?谢谢你。
Is there any easy method to achieve that? Thanks.
推荐答案
?只要这两个标签不会在XML出现,这会奏效。
Why don't you use one private field and use two different getters/setters? As long as both tags do not appear in the XML, this will work.
[XmlRoot("customers")]
public class CustomerList {
[XmlElement("customer")]
public Customer[] Customers { get; set; }
}
public class Customer {
private String _id;
[XmlElement("name")]
public String Name {get; set;}
[XmlElement("id")]
public String Id {get{return _id;} set{_id = value;}}
[XmlElement("code")]
public String Code {get{return _id;} set{_id = value;}}
}
这篇关于XML反序列化:不同的XML架构映射到同一个C#类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!