微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

反序列化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和我的对象之间的映射。

为每个元素创建一个类,每个元素都有一个属性,并为每个子元素创建一个List或Array对象(使用创建的对象)。然后调用System.Xml.Serialization.XmlSerializer.Deserialize的字符串,并将结果作为您的对象。使用System.Xml.Serialization属性进行调整,例如将元素映射到TodoList类,使用XmlElement(“todo-list”)属性

一个shocutcut是加载你的XML到Visual Studio,点击“Infer Schema”按钮,运行“xsd.exe / c schema.xsd”来生成类。 xsd.exe是在工具文件夹中。然后通过生成代码并进行调整,例如在适当的时候将shorts更改为ints。

原文地址:https://www.jb51.cc/xml/293950.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。