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;

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

6 Comments

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.
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 - web.archive.org/web/20130921190426/http://tech.pro/tutorial/798/… I don't see any problems here....
Dead link, downvoted, sorry (I know this was covered in the comments above but your answer hasn't been edited)
@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....
|
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

1 Comment

yep, xml serialization would be easiest

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.