如何将 XML 文件内容映射到 C# 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9336851/
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
How to map XML file content to C# object(s)
提问by temelm
I am new to C# and I am trying to read an XML file and transfer its contents to C# object(s).
我是 C# 新手,我正在尝试读取 XML 文件并将其内容传输到 C# 对象。
e.g. An example XML file could be:
例如,一个 XML 文件示例可以是:
<people>
<person>
<name>Person 1</name>
<age>21</age>
</person>
<person>
<name>Person 2</name>
<age>22</age>
</person>
</people>
.. could be mapped to an array of C# class called 'Person':
.. 可以映射到名为“Person”的 C# 类数组:
Person[] people;
Where a Person object could contain the following fields:
Person 对象可以包含以下字段:
string name;
uint age;
采纳答案by Justin Pihony
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
听起来您想使用 XML 序列化。已经有很多了,但这是一个非常简单的例子。 http://www.switchonthecode.com/tutorials/csharp-tutorial-xml-serialization
The snippet you want is about 1/4 of the way down:
您想要的代码段大约是向下的 1/4:
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();
Hopefully, this helps
希望这会有所帮助
回答by Jomit
You can use the XmlSerializer class to serialize CLR Objects into XML. Here is the MSDN documentation with some sample code : http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx
您可以使用 XmlSerializer 类将 CLR 对象序列化为 XML。这是带有一些示例代码的 MSDN 文档:http: //msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx

