Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
like image 462
temelm Avatar asked Feb 17 '12 23:02

temelm


People also ask

Which class is used in C for writing an XML file?

XmlWriter class contains the functionality to write to XML documents. It is an abstract base class used through XmlTextWriter and XmlNodeWriter classes. It contains methods and properties to write to XML documents.


1 Answers

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

like image 188
Justin Pihony Avatar answered Sep 18 '22 17:09

Justin Pihony