将 XML 字符串解析为 C# 中的类?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11300739/
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-09 17:18:31  来源:igfitidea点击:

Parse XML string to class in C#?

c#.netxmlclass

提问by Vivian River

Possible Duplicate:
How to Deserialize XML document

可能的重复:
如何反序列化 XML 文档

Suppose that I have a class that is defined like this in C#:

假设我有一个在 C# 中定义如下的类:

public class Book
{
    public string Title {get; set;}
    public string Subject {get; set;}
    public string Author {get; set;}
}

Suppose that I have XML that looks like this:

假设我有如下所示的 XML:

<Book>
    <Title>The Lorax</Title>
    <Subject>Children's Literature</Subject>
    <Author>Theodor Seuss Geisel</Author>
<Book>

If I would like to instantiate an instance of the Bookclass using this XML, the only way I know of to do this is to use the XML Document class and enumerate the XML nodes.

如果我想Book使用此 XML实例化类的实例,我所知道的唯一方法是使用 XML Document 类并枚举 XML 节点。

Does the .net framework provide some way of instantiating classes with XML code? If not, what are the best practices for accomplishing this?

.net 框架是否提供了一些用 XML 代码实例化类的方法?如果没有,实现这一目标的最佳实践是什么?

采纳答案by Steven Doggart

You can just use XML serialization to create an instance of the class from the XML:

您可以使用 XML 序列化从 XML 创建类的实例:

XmlSerializer serializer = new XmlSerializer(typeof(Book));
using (StringReader reader = new StringReader(xmlDocumentText))
{
    Book book = (Book)(serializer.Deserialize(reader));
}

回答by Oded

There are several ways to deserialize an XML document - the XmlSerializerliving in System.Xml.Serializationand the newer DataContractSerializerwhich is in System.Runtime.Serialization.

有几种方法来反序列化的XML文档-在XmlSerializer生活中System.Xml.Serialization和更新的DataContractSerializer这是System.Runtime.Serialization

Both require that you decorate your class members with attributes that tell the serializer how to operate (different attributes for each).

两者都要求您使用告诉序列化程序如何操作的属性(每个属性不同)来装饰您的类成员。