解析XML字符串类在C#中? [英] Parse XML string to class in C#?

查看:451
本文介绍了解析XML字符串类在C#中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

假设我有这样定义在C#中的一类:

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;}
}

假设我有XML看起来像这样的:

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>

如果我想使用此XML实例的图书类的一个实例,我所知道的唯一的方式做,这是使用XML文档类和枚举的XML节点

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.

是否在.NET Framework提供了实例化类与XML code的一些方法?如果没有,什么是实现这一目标的最佳做法是什么?

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

推荐答案

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

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));
}

这篇关于解析XML字符串类在C#中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆