c# - 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.
解决方案
您可以使用XmlSerializer将 xml 反序列化为 2 个单独的类。
创建 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; } }
创建一个反序列化类的简单通用函数。
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); } }
推荐阅读
- symfony - Symfony Messenger 在停止/消费之前不会消费消息
- jquery - jQuery 数据表主详细信息设置中的详细信息标题高度为零
- discord - 如何保存一些变量
- javascript - 数据表 - 手风琴(子行)
- ios - 集合视图单元格中的 UIButton 未收到 Touch Up Inside 事件
- angular - 在基于对象值的 API 调用之后在 typescript 中添加计算属性的最佳方法
- php - Laravel Sanctum 身份验证问题
- serial-port - 使用 PowerMockito 模拟 com.fazecast.jSerialComm.SerialPort 时出现 UnsupportedOperationException
- linq - Linq 连接表和可为空的变量
- javascript - 如何简化数组过滤器