简体   繁体   English

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

[英]Xml.Linq: Descendants() returns nothing

I am trying to read from an ncx file (ie xml file) using XElement: 我试图使用XElement从ncx文件(即xml文件)中读取:

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

As a result, foundNode is null because ncx.Descendants("navPoint") returns an empty enumeration. 因此,foundNode为null,因为ncx.Descendants(“navPoint”)返回空枚举。 But the data is there: 但数据是:

<?xml version='1.0' encoding='utf-8'?>
<ncx xmlns="http://www.daisy.org/z3986/2005/ncx/" version="2005-1" xml:lang="en">
  <head>
    <meta content="8eab2efe-d584-478a-8c73-1304d2ae98fa" name="dtb:uid"/>
    <meta content="3" name="dtb:depth"/>
    <meta content="calibre (0.8.12)" name="dtb:generator"/>
    <meta content="0" name="dtb:totalPageCount"/>
    <meta content="0" name="dtb:maxPageNumber"/>
  </head>
  <docTitle>
    <text>Fine</text>
  </docTitle>
  <navMap>
    <navPoint class="chapter" id="27665f37-ecf5-4934-a044-4f77152e54d9" playOrder="1">
      <navLabel>
        <text>I. BLIND</text>
      </navLabel>
      <content src="Fine_split_003.html"/>

Could you please explain what is wrong here? 你能解释一下这里有什么问题吗? Thanks. 谢谢。

You need to take namespace in XML into account: 您需要考虑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属性去除命名空间或引用元素而不使用命名空间: 此处的示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM