【问题标题】:C# Xpath can't get element by nameC# Xpath 无法按名称获取元素
【发布时间】:2019-02-03 09:16:31
【问题描述】:

使用下一个结构将文档加载到 XmlDocument

<?xml version="1.0" encoding="UTF-8"?>
<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink">
  <stylesheet type="text/css"></stylesheet>
  <description>...</description>
  <body>...</body>
  <binary id="19317.jpg" content-type="image/jpeg">...</binary>
</FictionBook>

下一个方法返回 null(如果我使用 SelectNodes,则返回空集合):

doc.SelectSingleNode("body");
doc.SelectSingleNode("//body");
doc.LastChild.SelectSingleNode("body");
doc.LastChild.SelectSingleNode("//body");

但是这个可以正常工作

doc.LastChild["body"];

为什么 XPath 不给我任何结果?

【问题讨论】:

    标签: c# xml xpath


    【解决方案1】:

    doc.SelectSingleNode("//body"); 不起作用,因为body 是在特定命名空间“http://www.gribuser.ru/xml/fictionbook/2.0”中声明的,因此要查询它,您可以这样编码:

    var mgr = new XmlNamespaceManager(new NameTable());
    mgr.AddNamespace("whatever", "http://www.gribuser.ru/xml/fictionbook/2.0");
    var node = doc.SelectSingleNode("//whatever:body", mgr);
    

    doc.LastChild["body"];工作,因为实现支持它,但你可以像这样使用它来避免歧义:

    doc.LastChild["body", "http://www.gribuser.ru/xml/fictionbook/2.0"]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-20
      • 2012-05-05
      • 1970-01-01
      • 2013-01-21
      • 1970-01-01
      相关资源
      最近更新 更多