c# - 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 不给我任何结果?
解决方案
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"]
推荐阅读
- javascript - 无法从 firebase 的 getDownloadURL 获取 URL
- r - 运行 draw.pairwise.venn 后取消消息
- android - Android - 切换 wifi 后,Exoplayer 无法离线下载
- python - 在 Geckodriver Python Selenium 上禁用 Strict Origin Policy
- asp.net-core - 在 asp.net core mvc 视图中绑定日期和时间
- oracle - 如何在 shell 脚本中连接到 Oracle DB 以执行多个 SQL 查询
- reactjs - React useState / setState错误:当多个组件实例在同一页面上时不是一个函数
- node.js - 填充后如何访问 $geowithin
- python-3.x - 在 python3 中根据用户输入查找节点
- r - R中的Sumif有条件