Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
111 views
in Technique[技术] by (71.8m points)

c# - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...