首页 > 解决方案 > 如果按 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 过滤,确实会填充。我不知所措:我尝试通过转义@、括号、等号来使其工作,什么都没有。有人可以帮我吗?

标签: javascriptxpathxmlhttprequestxmldom

解决方案


感谢@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)

推荐阅读