Xml.Linq:后代()不返回任何内容

发布于 2024-12-05 12:31:45 字数 1109 浏览 0 评论 0原文

我正在尝试使用 XElement 读取 ncx 文件(即 xml 文件):

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

结果,foundNode 为 null,因为 ncx.Descendants("navPoint") 返回空枚举。但数据就在那里:

<?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"/>

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

I am trying to read from an ncx file (i.e. xml file) using XElement:

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. 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

痞味浪人 2024-12-12 12:31:45

您需要考虑 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();

You need to take namespace in XML into account:

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();
随遇而安 2024-12-12 12:31:45

您还可以使用 XElement.Name.LocalName 属性删除命名空间或在不使用命名空间的情况下引用元素: 示例在这里

You can also strip out namespaces or refer to elements without using the namespace by using the XElement.Name.LocalName property: Examples here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文