阅读xml的最佳方式 [英] Best way to read through xml

查看:52
本文介绍了阅读xml的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的 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>

我想使用 XmlReader 来读取这个 xml 并将学生列表作为 List 返回.我知道这可以通过以下方式实现:

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?

我使用的是 silverlight 4.xml 结构是静态的,即.它将只有一个 Students 节点,并且所有具有上述属性的学生节点都只会在那里.

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.

推荐答案

绝对 - 使用 LINQ to XML.它要简单得多:

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 是一种相对低级的类型 - 我会避免使用它,除非您真的不能一次将整个 XML 放入内存中.即便如此,如果您只想要文档的子树,也可以将 LINQ to XML 与 XmlReader 结合使用.

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.

这篇关于阅读xml的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆