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

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

问题描述

所以,我对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(待办事项列表)属性。

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.

一个shourtcut是加载XML到Visual Studio中,单击推断模式按钮,然后运行XSD.EXE / C schema.xsd生成的类。 XSD.EXE在工具文件夹中。然后通过产生的code和做出调整,如更改短裤整数在适当情况下。

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.

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

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