【问题标题】:How to get xPath of an element, and retrieve the element again from the xPath如何获取元素的 xPath,并再次从 xPath 检索元素
【发布时间】:2017-08-20 21:58:22
【问题描述】:

我正在尝试创建一个用户可以在浏览器中存储注释的应用程序。

为了找出用户在文档中创建注释的位置,我尝试存储所选文本的 xpath 和偏移量。

我四处搜索,似乎有很多从 xPath 字符串中检索元素的示例,但不是从 DOM 元素中查找 xPath 的好示例。

这是我尝试过的:

//Find xPath and pass the object
var range_obj = {
  start: getXPathForElement(range.startContainer, range.startContainer.ownerDocument),
  end: getXPathForElement(range.endContainer, range.endContainer.ownerDocument),
  startOffset: range.startOffset,
  endOffset: range.endOffset
};

getXPathForElement 看起来像这样:

function getXPathForElement(el, xml) {
  var xpath = '';
  var pos, tempitem2;

  while (el !== xml.documentElement) {
    pos = 0;
    tempitem2 = el;
    while (tempitem2) {
      if (tempitem2.nodeType === 1 && tempitem2.nodeName === el.nodeName) { // If it is ELEMENT_NODE of the same name
        pos += 1;
      }
      tempitem2 = tempitem2.previousSibling;
    }

    xpath = "*[name()='" + el.nodeName + "' and namespace-uri()='" + (el.namespaceURI === null ? '' : el.namespaceURI) + "'][" + pos + ']' + '/' + xpath;

    el = el.parentNode;
  }
  xpath = '/*' + "[name()='" + xml.documentElement.nodeName + "' and namespace-uri()='" + (el.namespaceURI === null ? '' : el.namespaceURI) + "']" + '/' + xpath;
  xpath = xpath.replace(/\/$/, '');
  return xpath;
}

这段代码给出了一个很长很奇怪的文本,如下所示:(我认为这不是一个正确的 xPath)。

"/[name()='HTML' and namespace-uri()='http://www.w3.org/1999/xhtml']/[name()='BODY' and namespace-uri()=' http://www.w3.org/1999/xhtml'][1]/[name()='P' and namespace-uri()='http://www.w3.org/1999/xhtml'][1]/[name()='SPAN' and namespace-uri()='http://www.w3.org/1999/xhtml'][4]/[name()='SPAN' 和 namespace-uri()='http://www.w3.org/1999/xhtml'][2]/[name ()='#text' 和 namespace-uri()='undefined'][0]"

但在 Chrome Inspect Element 中,它给出了一些干净的字符串,如下所示:

//*[@id="tinymce"]/p/span[2]/span[2]/strong

谁能帮我从文档中检索元素的 xpath,然后稍后从 xpath 中找到该元素?

【问题讨论】:

    标签: javascript jquery html xml xpath


    【解决方案1】:

    如果您能够使用 Saxon-JS,那么您可以使用专门为此目的设计的 XPath 3.0 函数 fn:path()。

    【讨论】:

      猜你喜欢
      • 2016-01-19
      • 1970-01-01
      • 1970-01-01
      • 2011-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-30
      相关资源
      最近更新 更多