Skip to main content
 首页 » 编程设计

c#之使用 Linq to XML 时查询 xml 返回 null

2024年02月23日13pander-it

我在文件中有以下 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. 

请您参考如下方法:

下面是一个适用于您的 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); 
}