在使用JavaScript中的XPath查询获取节点之后,获取节点的完整路径

时间:2010-06-18 17:41:28

标签: javascript xml xpath

我在JavaScript中有下一条指令:

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

所以我的问题是如何获得节点firstscene的完整路径?

1 个答案:

答案 0 :(得分:0)

使用此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;
  };

将从firstScene.iterateNext()获取的DOM ojbect传递给getXPath()方法,它将返回一个包含所有XPATH步骤的数组。

然后,您可以使用数组join()方法返回完整的XPATH表达式:

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