Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to read through xml

HI I have a xml document like this:

<Students>
<student name="A" class="1"/>
<student name="B"class="2"/>
<student name="c" class="3"/>
</Students>

I want to use XmlReader to read through this xml and return a list of students as List<student>. I know this can be achieved as follows:

 List<Student> students = new List<Student>();
    XmlReader reader = XmlReader.Create("AppManifest.xml");
    while (reader.Read())
    {
       if (reader.NodeType == XmlNodeType.Element && reader.Name == "student")
       {
            students.Add(new Student()
            {
                 Name = reader.GetAttribute("name"),
                 Class = reader.GetAttribute("Class")
             });
        }
     }

I just want to know if there is any better solution for this?

I am using silverlight 4. The xml structure is static, ie. it will have only one Students node and all the student node with above said attributes will only be there.

like image 714
Chinjoo Avatar asked Mar 04 '11 15:03

Chinjoo


People also ask

What is the best way to view XML files?

View an XML file in a browser If all you need to do is view the data in an XML file, you're in luck. Just about every browser can open an XML file. In Chrome, just open a new tab and drag the XML file over. Alternatively, right click on the XML file and hover over "Open with" then click "Chrome".

Which method is used to read XML documents?

Java DOM Parser The DOM API provides the classes to read and write an XML file. We can create, delete, modify, and rearrange the node using the DOM API. DOM parser parses the entire XML file and creates a DOM object in the memory. It models an XML file in a tree structure for easy traversal and manipulation.


2 Answers

Absolutely - use LINQ to XML. It's so much simpler:

XDocument doc = XDocument.Load("AppManifest.xml");
var students = doc.Root
                  .Elements("student")
                  .Select(x => new Student {
                              Name = (string) x.Attribute("name"),
                              Class = (string) x.Attribute("class")
                          })
                  .ToList();

XmlReader is a relatively low-level type - I would avoid it unless you really can't afford to slurp the whole of the XML into memory at a time. Even then there are ways of using LINQ to XML in conjunction with XmlReader if you just want subtrees of the document.

like image 84
Jon Skeet Avatar answered Sep 19 '22 17:09

Jon Skeet


It's alot easier if we're using Linq xml:

var xDoc = XDocument.Load("AppManifest.xml");

var students = 
    xDoc.Root.Elements("student")
    .Select(n =>
        new Student
        {
            Name = (string)n.Attribute("name"),
            Class = (string)n.Attribute("class"),
        })
    .ToList();
like image 39
Torbjörn Hansson Avatar answered Sep 17 '22 17:09

Torbjörn Hansson