You are viewing a plain text version of this content. The canonical link for it is here.
Posted to c-dev@xerces.apache.org by "Stratton, Jason" <js...@telegea.com> on 2000/09/29 23:20:59 UTC

XPath

Could someone please tell me how to get the XPath for a given DOM_Node?

Thank you.
Jason Stratton
jstratton@telegea.com

Re: XPath

Posted by "Perry A. Caro" <ca...@Adobe.COM>.
"Stratton, Jason" wrote:
> 
> Could someone please tell me how to get the XPath for a given DOM_Node?

I've written this code umpteem times in different languages and DOM API's,
but I haven't gotten around to doing it for Xerces-C yet.  Nevertheless,
it's pretty straightforward, so I'll try some pseudo-code below.

First, remember that XPath is many-to-one: there are many valid XPaths to
any given node.  If all you want is the abbreviated implicit axes XPath that
most people use, just do something like the following (for attributes and
elements only, other nodes like PIs need a little special handling):

	* Initialize xpath to empty
	* Get your node
LOOP:
	* If node is root
		* Then finish xpath (prepend "/"?), DONE.
	* name = the node's name
	* If the node is an Attribute, name = "@" + name
	* If xpath is empty
		* Then xpath = name
		* Else xpath = name + "/" + xpath
	* If the node is an Attribute
		* Then node = element containing attribute node
		* Else node = parent of node
	* Goto LOOP

If you are using namespaces, and nodes in the path are from different
namespaces, you may have to do more work to deal with QNames, which is left
as an exercise for the reader. :-)  It would be nice to have a fully
namespace aware utility function in Xerces-C to do this ... I'm not
volunteering! :-)

Perry