在 C# 中将 XML 反序列化为对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/226599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 18:57:26  来源:igfitidea点击:

Deserializing XML to Objects in C#

c#.netserialization

提问by Justin Bozonier

So I have xml that looks like this:

所以我有一个看起来像这样的 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>

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

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

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

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

采纳答案by Dan Goldstein

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.

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

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 加载到 Visual Studio 中,单击“Infer Schema”按钮并运行“xsd.exe /c schema.xsd”以生成类。xsd.exe 位于工具文件夹中。然后检查生成的代码并进行调整,例如在适当的情况下将 shorts 更改为 ints。

回答by Steve Horn

Boils down to using xsd.exe from tools in VS:

归结为使用 VS 中的工具中的 xsd.exe:

xsd.exe "%xsdFile%" /c /out:"%outDirectory%" /l:"%language%"

Then load it with reader and deserializer:

然后用读取器和解串器加载它:

public GeneratedClassFromXSD GetObjectFromXML()
{
    var settings = new XmlReaderSettings();
    var obj = new GeneratedClassFromXSD();
    var reader = XmlReader.Create(urlToService, settings);
    var serializer = new System.Xml.Serialization.XmlSerializer(typeof(GeneratedClassFromXSD));
    obj = (GeneratedClassFromXSD)serializer.Deserialize(reader);

    reader.Close();
    return obj;
}

回答by Joel Coehoorn

There are a couple different options.

有几个不同的选择。

  • Visual Studio includes a command line program called xsd.exe. You use that program to create a schema document, and use the program again on the schema document to creates classes you can use with system.xml.serialization.xmlserializer
  • You might just be able to call Dataset.ReadXml() on it.
  • Visual Studio 包含一个名为 xsd.exe 的命令行程序。您使用该程序创建模式文档,然后在模式文档上再次使用该程序来创建您可以使用的类system.xml.serialization.xmlserializer
  • 您可能只能对其调用 Dataset.ReadXml() 。

回答by Joel Coehoorn

Well, you'd have to have classes in your assembly that match, roughly, the XML (property called Private, a collection property called ToDo, etc).

好吧,您的程序集中必须有与 XML 大致匹配的类(称为 Private 的属性,称为 ToDo 的集合属性等)。

The problem is that the XML has elements that are invalid for class names. So you'd have to implement IXmlSerializable in these classes to control how they are serialized to and from XML. You might be able to get away with using some of the xml serialization specific attributes as well, but that depends on your xml's schema.

问题在于XML 包含对类名无效的元素。因此,您必须在这些类中实现 IXmlSerializable 以控制它们与 XML 之间的序列化方式。您也可以使用一些特定于 xml 序列化的属性,但这取决于您的 xml 架构。

That's a step above using reflection, but it might not be exactly what you're hoping for.

这是使用反射的上述步骤,但它可能不是您所希望的。

回答by Deepfreezed

Checkout http://xsd2code.codeplex.com/

结帐http://xsd2code.codeplex.com/

Xsd2Code is a CSharp or Visual Basic Business Entity class Generator from XSD schema.

Xsd2Code 是来自 XSD 架构的 CSharp 或 Visual Basic 业务实体类生成器。

回答by Keith

Deserialize any object, as long as the type Tis marked Serializable:

反序列化任何对象,只要类型T被标记为可序列化:

function T Deserialize<T>(string serializedResults)
{
    var serializer = new XmlSerializer(typeof(T));
    using (var stringReader = new StringReader(serializedResults))
        return (T)serializer.Deserialize(stringReader);
}

回答by Savaratkar

i had the same questions few years back that how abt mapping xml to C# classes or creating C# classes which are mapped to our XMLs, jst like we do in entity Framework (we map tables to C# classes). I created a framework finally, which can create C# classes out of your XML and these classes can be used to read/write your xml. Have a look

几年前我有同样的问题,即如何将 xml 映射到 C# 类或创建映射到我们的 XML 的 C# 类,就像我们在实体框架中所做的那样(我们将表映射到 C# 类)。我最终创建了一个框架,它可以从您的 XML 创建 C# 类,这些类可用于读/写您的 xml。有一个看看