简体   繁体   English

将同一节点下的XML元素反序列化为2个不同的对象

[英]Deserialize XML Elements which are under same node into 2 different Object

<root>
  <x_Name />
  <x_Age />
  <x_Gender />
  <x_addr1 />
  <x_addr2 />
  <x_city />
  <x_state />
  <x_country />
  <x_zip />
</root>

The above sample xml, I would like to deserialize the content into 2 objects such as Personal details that include (name, Age, and gender) and Contact Details that include (address details). 在上面的示例xml中,我想将内容反序列化为2个对象,例如包含(姓名,年龄和性别)的个人详细信息和包含(地址详细信息)的联系详细信息。

I could able to deserialize all the contect into a single object but I am unable to split into into 2 objects using xml deserialization. 我可以将所有内容反序列化为单个对象,但是无法使用xml反序列化将其拆分为2个对象。

You could use the XmlSerializer to deserialize the xml into 2 seperate classes. 您可以使用XmlSerializer将xml反序列化为2个单独的类。

  1. Create the 2 models: 创建2个模型:

     [XmlRoot("root", Namespace = "")] public class Personal { [XmlElement("x_Name", Namespace = "")] public string Name { get; set; } [XmlElement("x_Age", Namespace = "")] public string Age { get; set; } } [XmlRoot("root", Namespace = "")] public class Contact { [XmlElement("x_country", Namespace = "")] public string Country { get; set; } [XmlElement("x_zip", Namespace = "")] public string Zip { get; set; } } 
  2. Create a simple generic function that deserializes the class. 创建一个简单的泛型类反序列化。

     class Program { private static string _xml = @"c:\\temp\\myxml.xml"; static void Main(string[] args) { var personal = Deserialize<Personal>(_xml); var contact = Deserialize<Contact>(_xml); } public static T Deserialize<T>(string file) { var serializer = new XmlSerializer(typeof(T)); using (var xmlReader = XmlReader.Create(file)) return (T)serializer.Deserialize(xmlReader); } } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM