执行XQuery语句遇DOMException错误,如何统计XML唯一title数量?
问题:统计XML唯一title数量触发XPath非法表达式错误
统计XML文件中所有唯一<title>的数量时,触发以下错误:
Uncaught DOMException: Document.evaluate: The expression is not a legal expression
示例XML结构:
<channel> <item> <title>Trans Researchers Want Google Scholar to Stop Deadnaming Them</title> <link>https://www.wired.com/story/trans-researchers-want-google-scholar-to-stop-deadnaming-them/</link> <description>The academic search engine’s policy on name changes is out of step with other search tools and publishers.</description> <category>Business</category> <thumbnail>https://media.wired.com/photos/630fe159567860ab6c66c667/master/pass/business-deadnames-google.jpg</thumbnail> </item> <item> <title>Babylon Disrupted the UK’s Health System. Then It Left</title> <link>https://www.wired.com/story/babylon-disrupted-uk-health-system-then-left/</link> <description>The AI-powered online doctor app is ditching its controversial NHS contracts as it focuses on the US market.</description> <category>Business</category> <thumbnail>https://media.wired.com/photos/63042ca2f06d7dee6f53bbc6/master/pass/Babylon-Leaves-NHS-Business-1253255825.jpg</thumbnail> </item> </channel>
使用的JavaScript代码:
function displayCount() { // get the number of distinct titles using xquery var xquery = "count(distinct-values(/channel/item/title))"; var count = xmlFile.evaluate(xquery, xmlFile, null, XPathResult.ANY_TYPE, null); //document.getElementById("count").innerHTML = count.textContent; console.log(count.numberValue); }
错误原因
浏览器原生的Document.evaluate()仅支持XPath 1.0,而distinct-values()是XPath 2.0及以上版本才新增的函数,因此该表达式会被判定为非法。
修正方法
方法一:原生JavaScript手动去重计数
通过XPath获取所有<title>节点后,用Set数据结构自动去重,再统计数量,无需依赖高阶XPath特性:
function displayCount() { // 用XPath 1.0语法获取所有title节点 var xpathExpr = "/channel/item/title"; var nodeResult = xmlFile.evaluate(xpathExpr, xmlFile, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); // 提取title文本并去重 var uniqueTitles = new Set(); for (let i = 0; i < nodeResult.snapshotLength; i++) { const titleText = nodeResult.snapshotItem(i).textContent.trim(); uniqueTitles.add(titleText); } // 输出唯一title的数量 console.log(uniqueTitles.size); }
方法二:引入XPath 2.0支持库(可选)
若坚持使用distinct-values()这类XPath 2.0函数,可引入第三方库提供高阶XPath支持,但需要额外加载库并调整代码逻辑,不如原生方案轻便。
内容的提问来源于stack exchange,提问作者S. Tiss
相关产品推荐
相关产品推荐

