0

i have the next instruction, in JavaScript:

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

so my question is how to get the full path of the node firstscene?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
mjsr
  • 7,410
  • 18
  • 57
  • 83

1 Answers1

0

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("/");
Mads Hansen
  • 63,927
  • 12
  • 112
  • 147
  • it doesn't work, where you get all that properties? i debug the program and a XpathResult doesn't have definition for any of the things that you use, nodeType, nextSibling, previousSibling....The only thing that an iterator of XpathResult.ORDERED_NODE_ITERATOR_TYPE has is a method to move to the next result node iterateNext() and properties to access to the inner value. – mjsr Jun 20 '10 at 05:30
  • Sorry about that. I tested with the results of `document.getElementById`. I'll look and see if I can get it to evaluate properly with the results of the XPATH evaluation. – Mads Hansen Jun 20 '10 at 13:20
  • Looks like the `getXPath()` method expects a DOM Object and the result of the XPATH expression is not, but you can obtain it from the `iterateNext()` method. I have corrected my answer with something that worked for me. – Mads Hansen Jun 20 '10 at 14:43
  • well i test it and with iterateNext neither work, however using the property singleNodeValue that return an HTMLElement your function works!!!, thanks for the help....now i have just one little problem left....in some pages i have different frames so the contextNode (the second argument from evaluate) it's not document, so the query fails...i'm searching how to overcome that issue. – mjsr Jun 20 '10 at 17:29