将XML反序列化为C#中的对象
所以我有看起来像这样的xml:
<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#对象?
当前,我正在使用反射,并使用命名约定在xml和对象之间进行映射。
回答:
为每个元素创建一个类,每个类具有一个属性,每个子元素具有一个对象列表或对象数组(使用创建的对象)。然后在字符串上调用System.Xml.Serialization.XmlSerializer.Deserialize,并将结果转换为对象。使用System.Xml.Serialization属性进行调整,例如将元素映射到ToDoList类,请使用XmlElement(“
todo-list”)属性。
一个简单的方法是将XML加载到Visual Studio中,单击“推断模式”按钮,然后运行“ xsd.exe / c
schema.xsd”以生成类。xsd.exe是在tools文件夹中。然后遍历生成的代码并进行调整,例如在适当的地方将short更改为int。
以上是 将XML反序列化为C#中的对象 的全部内容, 来源链接: utcz.com/qa/402381.html







