Parse XML string to class in C#? [duplicate]

2019-03-08 22:02发布

Possible Duplicate:
How to Deserialize XML document

Suppose that I have a class that is defined like this in 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:

<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 Book class using this XML, the only way I know of to do this is to use the XML Document class and enumerate the XML nodes.

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

标签: c# .net xml class
2条回答
爷的心禁止访问
2楼-- · 2019-03-08 22:39

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

XmlSerializer serializer = new XmlSerializer(typeof(Book));
using (StringReader reader = new StringReader(xmlDocumentText))
{
    Book book = (Book)(serializer.Deserialize(reader));
}
查看更多
闹够了就滚
3楼-- · 2019-03-08 22:43

There are several ways to deserialize an XML document - the XmlSerializer living in System.Xml.Serialization and the newer DataContractSerializer which is in System.Runtime.Serialization.

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

查看更多
登录 后发表回答