javascript - 如果按 xml:id 过滤,则 document.evaluate 中的 XPath 返回空
问题描述
我有这个.xml:
[...]<person xml:id="pe_054">
<persName>
<forename>Robert</forename>
<surname>Thomas</surname>
</persName>
</person>[etc]
我有这个 JavaScript:
[...]function resolver() {
return 'http://www.tei-c.org/ns/1.0';
}
Connect.open("GET", "data/persons_places.xml", false);
Connect.setRequestHeader("Content-Type", "text/xml");
Connect.send(null);
var xmldoc = Connect.responseXML;
const surname = xmldoc.evaluate('//tei:person/tei:persName/tei:surname', xmldoc, resolver, XPathResult.STRING_TYPE, null)[...]
它按预期工作,即它返回第一个“姓”节点的文本内容。不过,我需要通过 @xml:id 属性获取特定的姓氏。因此,如果我将 XPath 编辑为此:
const surname = xmldoc.evaluate('//tei:person[@xml:id='pe_001']/tei:persName/tei:surname', xmldoc, resolver, XPathResult.STRING_TYPE, null)
该代码返回一个空字符串。在 console.log 我得到:
XPathResult { resultType: 2, stringValue: "", invalidIteratorState: false }
stringValue
如果我不按@xml:id 过滤,确实会填充。我不知所措:我尝试通过转义@、括号、等号来使其工作,什么都没有。有人可以帮我吗?
解决方案
感谢@supputuri,我意识到这只是 xml 命名空间的问题。所以,工作代码是:
function nsResolver(prefix) {
var ns = {
'xml' : 'http://www.w3.org/XML/1998/namespace',
'tei': 'http://www.tei-c.org/ns/1.0'
};
return ns[prefix] || null;
}
const Connect = new XMLHttpRequest();
Connect.open("GET", "data/persons_places.xml", false);
Connect.setRequestHeader("Content-Type", "text/xml");
Connect.send(null);
var xmldoc = Connect.responseXML;
const surname = xmldoc.evaluate('string(//tei:person[@xml:id="pe_054"]/tei:persName/tei:surname)', xmldoc, nsResolver, XPathResult.STRING_TYPE, null)
推荐阅读
- html - 托管在 firebase 托管上的 html 页面上的视频无法在 Safari 上运行
- node.js - How to use multiple andWhere with knex in Node app?
- python - 如何获取 Python 列表的切片以组合连续元素?
- r - 如何在 google-collaboration 上安装 rgdal 和/或上传栅格
- javascript - 如何遍历 JSON 模式并将所有值设置为空字符串?
- excel - 如何在 VBA 的 for 循环中索引 excel 工作表函数的参数?
- html - 如何将文本相对于另一个文本的单个字母居中?
- video - 使用ffmpeg按大小和名称和名称拆分视频文件
- r - Survminer,生存包:“survdiff”对数秩和“常规”对数秩测试有什么区别?
- javascript - 邮递员测试是否填写了所需的输入