Building the xpath of a node with Jscript

O

olivier

I required to build the Xpath of a node and saw that it was sometimes asked
in this list. It's not really difficult but has I got some problem to write
it because of the attribute case, here is the solution.

function findXpath(node)
// build the xpath of an OnContextChange node
(InfoPath.DocContextChangeEventObject.Context)
{ var loop=true;
var path = node.nodeName; // remember current node name

if (node.nodeTypeString == "attribute") // attribute is a special case
{ path="/@"+path; // add attribute sign to the name
node=node.selectSingleNode("parent::*"); // select parent of attribute
path=node.nodeName+path; // add "real" nodename to the attribute name
}
while (loop) // loop for all nodenames
{ try
{ node = node.parentNode; // select parent
if (node.nodeName == "#document")
{ path = "//"+ path; // root found
loop = false;
}
else
{ path = node.nodeName + "/"+ path; // add new nodename
}
}
catch(e)
{ loop=false;
}
}
return path;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top