Xml.Linq:Descendants()什么都不返回

我试图使用XElement从ncx文件(即xml文件)中读取:

XElement foundNode = ncx.Descendants("navPoint").Where(r => r.Attribute("class").Value == "chapter").FirstOrDefault(); 

因此,foundNode为null,因为ncx.Descendants(“navPoint”)返回空枚举。 但数据是:

           Fine     I. BLIND   

你能解释一下这里有什么问题吗? 谢谢。

您需要将XML中的命名空间考虑在内:

 XDocument ncx = XDocument.Load("file.xml"); XNamespace df = ncx.Root.Name.Namespace; XElement foundNode = ncx.Descendants(df + "navPoint").Where(r => r.Attribute("class").Value == "chapter").FirstOrDefault(); 

您还可以使用XElement.Name.LocalName属性删除命名空间或引用元素而不使用命名空间: 此处的示例