首页 > 解决方案 > 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).

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.

标签: c#xml-parsingxml-deserialization

解决方案


您可以使用XmlSerializer将 xml 反序列化为 2 个单独的类。

  1. 创建 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. 创建一个反序列化类的简单通用函数。

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

推荐阅读