在 C# 中将 XML 反序列化为对象 [英] Deserializing XML to Objects in C#

查看:31
本文介绍了在 C# 中将 XML 反序列化为对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我的 xml 看起来像这样:

So I have xml that looks like this:

<todo-list>
  <id type="integer">#{id}</id>
  <name>#{name}</name>
  <description>#{description}</description>
  <project-id type="integer">#{project_id}</project-id>
  <milestone-id type="integer">#{milestone_id}</milestone-id>
  <position type="integer">#{position}</position>

  <!-- if user can see private lists -->
  <private type="boolean">#{private}</private>

  <!-- if the account supports time tracking -->
  <tracked type="boolean">#{tracked}</tracked>

  <!-- if todo-items are included in the response -->
  <todo-items type="array">
    <todo-item>
      ...
    </todo-item>
    <todo-item>
      ...
    </todo-item>
    ...
  </todo-items>
</todo-list>

我将如何使用 .NET 的序列化库将其反序列化为 C# 对象?

How would I go about using .NET's serialization library to deserialize this into C# objects?

目前我正在使用反射,并使用命名约定在 xml 和我的对象之间进行映射.

Currently I'm using reflection and I map between the xml and my objects using the naming conventions.

推荐答案

为每个元素创建一个类,为每个元素创建一个属性,并为每个子元素创建一个对象列表或数组(使用创建的对象).然后在字符串上调用 System.Xml.Serialization.XmlSerializer.Deserialize 并将结果转换为您的对象.使用 System.Xml.Serialization 属性进行调整,例如将元素映射到 ToDoList 类,使用 XmlElement("todo-list") 属性.

Create a class for each element that has a property for each element and a List or Array of objects (use the created one) for each child element. Then call System.Xml.Serialization.XmlSerializer.Deserialize on the string and cast the result as your object. Use the System.Xml.Serialization attributes to make adjustments, like to map the element to your ToDoList class, use the XmlElement("todo-list") attribute.

快捷方式是将您的 XML 加载到 Visual Studio,单击推断架构"按钮并运行xsd.exe/c schema.xsd"以生成类.xsd.exe 位于工具文件夹中.然后检查生成的代码并进行调整,例如在适当的情况下将 shorts 更改为 ints.

A shourtcut is to load your XML into Visual Studio, click the "Infer Schema" button and run "xsd.exe /c schema.xsd" to generate the classes. xsd.exe is in the tools folder. Then go through the generated code and make adjustments, such as changing shorts to ints where appropriate.

这篇关于在 C# 中将 XML 反序列化为对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆