Here's something that works, but will probably have low performance. I'm
only interested in elements, so haven't worked on other kinds of Nodes.
This is for use with XPathAPI, which insists on all element nodes having a
prefix (e.g. ":elementName").
public static String getPathFromRoot(Element e) {
Node p = e.getParentNode();
StringBuffer path = new StringBuffer();
try {
if (p.getNodeType() == Node.ELEMENT_NODE ) {
path.append(getPathFromRoot((Element)p));
}
path.append("/");
String n = XPathAPI.eval(e, "name()").toString();
// name() puts in no colon if no prefix, but XPathAPI needs
// colon for default namespace
if (n.indexOf(":") < 0) {
path.append(":");
}
path.append(n);
path.append("[");
path.append(XPathAPI.eval(e, "1 +
count(preceding-sibling::.)"));
path.append("]");
return path.toString();
} catch (Exception ex) {
ex.printStackTrace(System.err);
System.exit(-63);
}
return "";
}
----- Original Message -----
From: "Joseph Kesselman" <[EMAIL PROTECTED]>
To: "Jeff Greif" <[EMAIL PROTECTED]>
Cc: <[EMAIL PROTECTED]>
Sent: Tuesday, November 26, 2002 6:45 AM
Subject: Re: xpath constructor
> >Is there a utility in Xalan that, given a dom, will construct an XPath
> >(string or some other representation) from the root to a given node?
>
> I don't believe so. Proposed solutions have been posted to this mailing
> list; check the archives.
>
> There's an open question re where to put such a routine -- does it belong
> with the DOM impelementation (eg in Xerces), with the XPath implementation
> (eg in Xalan), or in a utility package (which would probably make the
> xml-commons project the right host)? I'd lean slightly toward xml-commons,
> simply because it should be made reusable with any implementation of
> either DOM or XPath.
>
> As you noted, the hardest part of doing this properly is
> generating/reconciling the list of prefixes needed by the XPath.
>
> ______________________________________
> Joe Kesselman / IBM Research
>