使用Linq to XML时,查询xml会返回null

时间:2011-05-12 23:03:23

标签: c# linq-to-xml

我在文件中有以下xml:

<Person>
    <Name first="John" last="Doe" />
</Person>

我使用XDocument.Load加载了xml文档,但我似乎无法获取第一个和最后一个属性的值。

我试过了:

var q = from n in rq.Element("Name")
        select n;  //but q is null after this.

1 个答案:

答案 0 :(得分:4)

以下是适用于您的XML文件的示例:

var doc = XDocument.Load(...);

var query = from node in doc.Root.Elements("Name")
            select new           //      ↑
            {
                First = (string)node.Attribute("first"),
                Last  = (string)node.Attribute("last")
            };

foreach (var item in query)
{
    Console.WriteLine("{1}, {0}", item.First, item.Last);
}