How to map XML file content to C# object(s)

≯℡__Kan透↙ 提交于 2019-12-03 23:46:46

问题


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

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>

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

    Person[] people;

Where a Person object could contain the following fields:

    string name;
    uint age;

回答1:


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

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

Hopefully, this helps




回答2:


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



来源:https://stackoverflow.com/questions/9336851/how-to-map-xml-file-content-to-c-sharp-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!