开发者

Get the full path of a node, after get it with an XPath query in JavaScript

开发者 https://www.devze.com 2023-01-04 12:18 出处:网络
i have the next instruction, in JavaScript: var firstScene = document.evaluate(\'//Scene\', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);

i have the next instruction, in JavaScript:

var firstScene = document.evaluate('//Scene', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);

so m开发者_如何学JAVAy question is how to get the full path of the node firstscene?


Using this getXPath() function:

  function getXPath(node, path) {
    path = path || [];
    if(node.parentNode) {
      path = getXPath(node.parentNode, path);
    }

    if(node.previousSibling) {
      var count = 1;
      var sibling = node.previousSibling
      do {
        if(sibling.nodeType == 1 && sibling.nodeName == node.nodeName) {count++;}
        sibling = sibling.previousSibling;
      } while(sibling);
      if(count == 1) {count = null;}
    } else if(node.nextSibling) {
      var sibling = node.nextSibling;
      do {
        if(sibling.nodeType == 1 && sibling.nodeName == node.nodeName) {
          var count = 1;
          sibling = null;
        } else {
          var count = null;
          sibling = sibling.previousSibling;
        }
      } while(sibling);
    }

    if(node.nodeType == 1) {
      path.push(node.nodeName.toLowerCase() + (node.id ? "[@id='"+node.id+"']" : count > 0 ? "["+count+"]" : ''));
    }
    return path;
  };

pass the DOM ojbect obtained from firstScene.iterateNext() to the getXPath() method and it will return an array with all of the XPATH steps.

You can then use the array join() method to return a full XPATH expression:

getXPath(firstScene.iterateNext()).join("/");
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号