如何将XML文件内容映射到C#对象 [英] How to map XML file content to C# object(s)

查看:192
本文介绍了如何将XML文件内容映射到C#对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C#的新手,我正在尝试读取一个XML文件并将其内容传递给C#对象。

I am new to C# and I am trying to read an XML file and transfer its contents to C# object(s).

一个示例XML文件可以是:

e.g. An example XML file could be:

    <people>
        <person>
            <name>Person 1</name>
            <age>21</age>
        </person>
        <person>
            <name>Person 2</name>
            <age>22</age>
        </person>
    </people>

..可以映射到名为Person的C#类数组:

.. could be mapped to an array of C# class called 'Person':

    Person[] people;

Person对象可能包含以下字段:

Where a Person object could contain the following fields:

    string name;
    uint age;


推荐答案

这听起来像是要使用XML序列化。有很多已经在那里,但这是一个非常简单的例子。
http //www.switchonthecode.com/tutorials/csharp-tutorial-xml-serialization

It sounds like you want use XML serialization. There is a lot already out there, but this is a pretty simple example. http://www.switchonthecode.com/tutorials/csharp-tutorial-xml-serialization

您所需的代码片段大概是1/4的下拉:

The snippet you want is about 1/4 of the way down:

XmlSerializer deserializer = new XmlSerializer(typeof(List<Movie>));
TextReader textReader = new StreamReader(@"C:\movie.xml");
List<Movie> movies; 
movies = (List<Movie>)deserializer.Deserialize(textReader);
textReader.Close();

希望这有助于

这篇关于如何将XML文件内容映射到C#对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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