gpt4 book ai didi

javascript - 将 XPath 转换为节点

转载 作者:行者123 更新时间:2023-11-30 05:59:32 26 4
gpt4 key购买 nike

我想知道如何将 XPath 转换为 Node 对象?

我问的原因是因为我正在尝试创建一个 Range 对象,并使用 XPath 设置范围。下面是我编写的代码,但根据我的理解,它不会工作,因为 setRange() 和 setEnd() 需要一个 Node 对象作为其第一个参数。

var range = document.createRange();
range.setStart(startXPath, startOffset);
range.setEnd(endXPath, endOffset);

编辑:这就是我获取 XPath 的方式:

function grabSelection() {
var selection = window.getSelection();
var range = selection.getRangeAt(0);

var selectObj = {
'startXPath': makeXPath(range.startContainer),
'startOffset': range.startOffset,
'endXPath': makeXPath(range.endContainer),
'endOffset': range.endOffset
}

return selectObj
}


function makeXPath (node, currentPath) {
currentPath = currentPath || '';
switch (node.nodeType) {
case 3:
case 4:
return makeXPath(node.parentNode, 'text()[' + (document.evaluate('preceding-sibling::text()', node, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotLength + 1) + ']');
case 1:
return makeXPath(node.parentNode, node.nodeName + '[' + (document.evaluate('preceding-sibling::' + node.nodeName, node, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotLength + 1) + ']' + (currentPath ? '/' + currentPath : ''));
case 9:
return '/' + currentPath;
default:
return '';
}
}

最佳答案

假设你称为“XPath”的东西是 XPath 查询的结果,这将返回一个 DOMNodelist,所以你必须设置

startXPath to XPathResult[0] 

endXPath to XPathResult[XPathResult.length-1]

(其中 XPathResult 是 XPath->query 返回的节点列表)


编辑评论相关内容

由于 startXPath 和 endXPath 确实是 XPath,您需要计算它们以获取节点:

  var startXPath = document.evaluate(startXPath, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(0);
var endXPath = document.evaluate(endXPath, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(0);

您能否解释一下您尝试实现的目标,也许有更好的方法?

关于javascript - 将 XPath 转换为节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9508148/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com