18

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;
Morteza Jalambadani
  • 2,190
  • 6
  • 21
  • 35
temelm
  • 826
  • 4
  • 15
  • 34

2 Answers2

27

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

Justin Pihony
  • 66,056
  • 18
  • 147
  • 180
  • 2
    The link to the xml-serialization code sample is now defunct... too bad. I think this is why people discourage linking to external sites on stackoverflow - but I too am a previous offender of this fopaux so am not really one to talk. – Shawn J. Molloy Aug 15 '15 at 19:28
  • I posted the pertinent code in case the link died. Also, you can either google that code for the rest, or even try the wayback machine - https://web.archive.org/web/20130921190426/http://tech.pro/tutorial/798/csharp-tutorial-xml-serialization I don't see any problems here.... – Justin Pihony Aug 16 '15 at 06:24
  • 1
    http://web.archive.org/web/20130921190426/http://tech.pro/tutorial/798/csharp-tutorial-xml-serialization - wayback machine link – Peter Clotworthy Oct 16 '15 at 18:24
  • Dead link, downvoted, sorry (I know this was covered in the comments above but your answer hasn't been edited) –  Jul 13 '16 at 08:06
  • 2
    @JᴀʏMᴇᴇ You have more than 2000 points, which means you could do it yourself. That is the goal of reputation and points. Bad form just downvoting a valid answer that you can fix.... – Justin Pihony Jul 13 '16 at 18:17
  • You need to remember to mark the object and its properties with the appropriate attributes [XmlRoot ("")], [XmlElement ("")], [XmlArray ("")]. – A510 Sep 11 '22 at 17:00
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

Jomit
  • 596
  • 3
  • 11