我正在尝试将 Javascript Document
evaluate
函数与有效的 XPath 一起使用,该 XPath 使用 name()
/ local-name()
函数,但在 Jfiddle 中始终出现以下错误:
The string '/foods/*[position()=1</a>/local-name()' is not a valid XPath expression
尚不清楚如何或为何引入
</a>
片段
示例代码如下:
const xml = "<foods><meat>chicken</meat><fruit>orange</fruit><fruit>apple</fruit><fruit>banana</fruit></foods>";
const doc = new DOMParser().parseFromString(xml,'application/xml');
for ( var i = 0 ; i < 4; i++ ){
const xpath = `/foods/*[position()=${i+1}]`;
const xpathValue = document.evaluate(
xpath,
doc,
null,
XPathResult.STRING_TYPE,
null
);
const xpathName = document.evaluate(
`${xpath}/local-name()`,
doc,
null,
XPathResult.STRING_TYPE,
null
);
console.log(`${xpathName.stringValue} = ${xpathValue.stringValue}`);
}
评估值的 XPath 工作正常,只是不能评估节点名称。任何帮助将不胜感激。
您可以将 XPath 3.1 与 SaxonJS 2 结合使用:
const xml = "<foods><meat>chicken</meat><fruit>orange</fruit><fruit>apple</fruit><fruit>banana</fruit></foods>";
const doc = new DOMParser().parseFromString(xml,'application/xml');
const result = SaxonJS.XPath.evaluate(`/foods/*/(name() || ':' || string())`, doc);
console.log(result);
<script src="https://martin-honnen.github.io/SaxonJS-2.6/SaxonJS2.js"></script>