首页 > 解决方案 > C# Xpath 无法按名称获取元素

问题描述

使用下一个结构将文档加载到 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#xmlxpath

解决方案


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"]

推荐阅读