[jdom-interest] What is a jdom context?

Laurent Bihanic laurent.bihanic at atosorigin.com
Tue Nov 7 09:14:26 PST 2006


Hi,

A context is any JDOM object (Document, Element, Comment, etc.) to be used as 
base for resolving the XPath expression.
If your XPath expression uses an absolute path ("/foo/bar/..."), the context 
object doesn't really matter as the XPath engine will look for the Document 
parent before starting the evaluation.
On the other hand, if the XPath is relative (e.g. "foo/bar" or "@foo"), the 
context shall be set to the correct JDOM object otherwise the XPath won't match.

To use the JDOM XPath object:
1. Compile the XPath expression into an object:
	XPath xpath = XPath.newInstance("foo/bar");
2. Evaluate the expression on a given context:
	Element bar = (Element)(xpath.selectSingleNode(document);
	List nodes = xpath.selectNodes(bar);

If you use your XPath expressions only once, you can avoid the compilation step:
	List nodes = xpath.selectNodes(document, "/foo/bar");

Note that Jaxan shall be present in your classpath.

Laurent

Syloke Soong a écrit :
> Given a jdom doc and a jdom xpath,
> I wish to extract whatever this xpath is pointing to in the doc.
> 
> The jdom javadoc for class XPath says,
> 
> selectNodes(java.lang.Object context, java.lang.String path) 
> Evaluates an XPath expression and returns the list of selected items.
> Parameters:
> context - the node to use as context for evaluating the XPath expression
> 
> 
> Well, what is a context or node? What should I use as argument context:
> I am thinking of possibilities:
> 1. A jdom Document
> 2. A jdom Element
> 3. A sax InputSource
> 4. All of the above
> 
> IMPHO (in my projected humble opinion) it would be convenient (at least
> for me) if context was a definite object similar to the way sax
> InputSource so we would know determinately what is acceptable as a
> "node" or "context".
> 
> Anyway, the question that led to this discussion is,
> How do I extract from a jdom document using a jdom xpath (without
> straying into jaxen).


More information about the jdom-interest mailing list