使用javascript将xpath相对于绝对xpath

时间:2016-03-30 22:44:16

标签: javascript dom xpath

是否可以使用javascript获取dom节点的相对位置的绝对xpath?

我找到的最接近的是指获取节点的xpath:Get Xpath from the org.w3c.dom.Node

此外,我获得没有唯一标识符的节点的相对xpath。任何想法如何解决这个问题?

例如,对于:

 <p>DUKE SOLINUS</p>
 <div>
 <p>AEGEON</p> 
 </div>

对于选定的单词&#34; DUKE&#34;和&#34; AEGEON&#34;,我得到xpaths&#34; / p [1]&#34;,AND&#34; / div [1] / p [1]&#34;分别,当传递给document.evaluate函数时,它们都评估到同一个节点&#34; DUKE SOLINUS&#34;。所以,我只有这些相对的xpath,并且没有节点。我想要的是评估这些相对的xpath来纠正节点,在这种情况下是两个不同的节点(DUKE SOLINUS和AEGEON)。

更具体地说,xpath取自json注释对象:http://docs.annotatorjs.org/en/v1.2.x/annotation-format.html

任何帮助将不胜感激! 非常感谢!

1 个答案:

答案 0 :(得分:0)

此函数将为给定节点找到基数绝对xpath。如果任何节点的顺序发生变化,或者添加或删除了节点,那么这将无法正常工作。但对于静态内容,应该没问题。

&#13;
&#13;
function getXpathOfNode(domNode,bits) {
  // uses cardinality.  Will not work if any nodes are added/moved/removed in the DOM.  Fine for static stuff.
  bits = bits ? bits : [];
  var c = 0;
  var b = domNode.nodeName;
  var p = domNode.parentNode;

  if (p) {
    var els = p.getElementsByTagName(b);
    if (els.length >  1) {
      while (els[c] !== domNode) c++;
      b += "[" + (c+1) + "]";
    }
    bits.push(b);
    return getXpathOfNode(p, bits);
  }
  
  //bits.push(b);  // this is #document.  Probably dont need it.
  return bits.reverse().join("/");
}
// testing
var xp = getXpathOfNode(document.getElementById("pickme"));
var r = document.getElementById("result");
r.innerHTML = "the xpath is " + xp + "<br>";
var result =  document.evaluate(xp, document, null, XPathResult.ANY_TYPE, null);
r.innerHTML += "the chosen node contains - " + result.iterateNext().innerHTML;
&#13;
<div>
<div>junk</div>
<span>irrelevant</span>
<div>pointless
<div>
<div id="pickme">this is the test node</div><span>don't read this</span></div>
<br><br>
<div id="result"></div>
</div>
&#13;
&#13;
&#13;