public abstract class JXPathContext extends Object
JXPathContext allows alternative implementations. This is why instead of
allocating JXPathContext directly, you should call a static
newContext
method. This method will utilize the
JXPathContextFactory
API to locate a suitable implementation of
JXPath. Bundled with JXPath comes a default implementation called Reference
Implementation.
In this example, we are using JXPath to access a property of thepublic class Employee { public String getFirstName(){ ... } } Employee emp = new Employee(); ... JXPathContext context = JXPathContext.newContext(emp); String fName = (String)context.getValue("firstName");
emp
bean. In this simple case the invocation of JXPath is
equivalent to invocation of getFirstName() on the bean.
In this case XPath is used to access a property of a nested bean.public class Employee { public Address getHomeAddress(){ ... } } public class Address { public String getStreetNumber(){ ... } } Employee emp = new Employee(); ... JXPathContext context = JXPathContext.newContext(emp); String sNumber = (String)context.getValue("homeAddress/streetNumber");
A property identified by the xpath does not have to be a "leaf" property. For instance, we can extract the whole Address object in above example:
Address addr = (Address)context.getValue("homeAddress");
A collection can be an arbitrary array or an instance of java.util. Collection.public class Integers { public int[] getNumbers(){ ... } } Integers ints = new Integers(); ... JXPathContext context = JXPathContext.newContext(ints); Integer thirdInt = (Integer)context.getValue("numbers[3]");
Note: in XPath the first element of a collection has index 1, not 0.
Often you will need to use the alternative syntax for accessing Map elements:public class Employee { public Map getAddresses(){ return addressMap; } public void addAddress(String key, Address address){ addressMap.put(key, address); } ... } Employee emp = new Employee(); emp.addAddress("home", new Address(...)); emp.addAddress("office", new Address(...)); ... JXPathContext context = JXPathContext.newContext(emp); String homeZipCode = (String)context.getValue("addresses/home/zipCode");
In this case, the key can be an expression, e.g. a variable.String homeZipCode = (String) context.getValue("addresses[@name='home']/zipCode");
JXPathIntrospector
.
getValue
, but iterate
.
This returns a list of at most three books from the array of all books written by the author.public class Author { public Book[] getBooks(){ ... } } Author auth = new Author(); ... JXPathContext context = JXPathContext.newContext(auth); Iterator threeBooks = context.iterate("books[position() < 4]");
public class Employee { public Address getAddress() { ... } public void setAddress(Address address) { ... } } Employee emp = new Employee(); Address addr = new Address(); ... JXPathContext context = JXPathContext.newContext(emp); context.setValue("address", addr); context.setValue("address/zipCode", "90190");
AbstractFactory
and install it on the JXPathContext. Then
call createPathAndSetValue()
instead of
"setValue". JXPathContext will invoke your AbstractFactory when it discovers
that an intermediate node of the path is null. It will not override
existing nodes.
public class AddressFactory extends AbstractFactory { public boolean createObject(JXPathContext context, Pointer pointer, Object parent, String name, int index){ if ((parent instanceof Employee) && name.equals("address"){ ((Employee)parent).setAddress(new Address()); return true; } return false; } } JXPathContext context = JXPathContext.newContext(emp); context.setFactory(new AddressFactory()); context.createPathAndSetValue("address/zipCode", "90190");
You can also set variables using JXPath:public class Author { public Book[] getBooks(){ ... } } Author auth = new Author(); ... JXPathContext context = JXPathContext.newContext(auth); context.getVariables().declareVariable("index", new Integer(2)); Book secondBook = (Book)context.getValue("books[$index]");
Note: you can only change the value of an existing variable this way, you cannot define a new variable.context.setValue("$index", new Integer(3));
When a variable contains a JavaBean or a collection, you can traverse the bean or collection as well:
... context.getVariables().declareVariable("book", myBook); String title = (String)context.getValue("$book/title); Book array[] = new Book[]{...}; context.getVariables().declareVariable("books", array); String title = (String)context.getValue("$books[2]/title);
JXPathContext varContext = JXPathContext.newContext(null); varContext.getVariables().declareVariable("title", "Java"); JXPathContext context = JXPathContext.newContext(varContext, auth); Iterator javaBooks = context.iterate("books[title = $title]");
Here's how you can create new objects:
Here's how you can call static methods:Book book = (Book) context.getValue( "org.apache.commons.jxpath.example.Book.new ('John Updike')");
Here's how you can call regular methods:Book book = (Book) context.getValue( "org. apache.commons.jxpath.example.Book.getBestBook('John Updike')");
As you can see, the target of the method is specified as the first parameter of the function.String firstName = (String)context.getValue("getAuthorsFirstName($book)");
Functions
objects or as Java classes, whose methods
become extenstion functions.
Let's say the following class implements various formatting operations:
We can register this class with a JXPathContext:public class Formats { public static String date(Date d, String pattern){ return new SimpleDateFormat(pattern).format(d); } ... }
You can also register whole packages of Java classes using PackageFunctions.context.setFunctions(new ClassFunctions(Formats.class, "format")); ... context.getVariables().declareVariable("today", new Date()); String today = (String)context.getValue("format:date($today, 'MM/dd/yyyy')");
Also, see FunctionLibrary
, which is a class
that allows you to register multiple sets of extension functions with
the same JXPathContext.
JXPathBeanInfo
).
Modifier and Type | Field and Description |
---|---|
protected Object |
contextBean
context bean
|
protected HashMap |
decimalFormats
decimal format map
|
protected AbstractFactory |
factory
AbstractFactory
|
protected Functions |
functions
functions
|
protected IdentityManager |
idManager
IdentityManager
|
protected KeyManager |
keyManager
KeyManager
|
protected JXPathContext |
parentContext
parent context
|
protected Variables |
vars
variables
|
Modifier | Constructor and Description |
---|---|
protected |
JXPathContext(JXPathContext parentContext,
Object contextBean)
This constructor should remain protected - it is to be overridden by
subclasses, but never explicitly invoked by clients.
|
Modifier and Type | Method and Description |
---|---|
static CompiledExpression |
compile(String xpath)
Compiles the supplied XPath and returns an internal representation
of the path that can then be evaluated.
|
protected abstract CompiledExpression |
compilePath(String xpath)
Overridden by each concrete implementation of JXPathContext
to perform compilation.
|
abstract Pointer |
createPath(String xpath)
Creates missing elements of the path by invoking an
AbstractFactory ,
which should first be installed on the context by calling setFactory(org.apache.commons.jxpath.AbstractFactory) . |
abstract Pointer |
createPathAndSetValue(String xpath,
Object value)
The same as setValue, except it creates intermediate elements of
the path by invoking an
AbstractFactory , which should first be
installed on the context by calling setFactory(org.apache.commons.jxpath.AbstractFactory) . |
Object |
getContextBean()
Returns the JavaBean associated with this context.
|
abstract Pointer |
getContextPointer()
Returns a Pointer for the context bean.
|
DecimalFormatSymbols |
getDecimalFormatSymbols(String name)
Get the named DecimalFormatSymbols.
|
AbstractFactory |
getFactory()
Returns the AbstractFactory installed on this context.
|
Functions |
getFunctions()
Returns the set of functions installed on the context.
|
IdentityManager |
getIdentityManager()
Returns this context's identity manager.
|
KeyManager |
getKeyManager()
Returns this context's key manager.
|
Locale |
getLocale()
Returns the locale set with setLocale.
|
Pointer |
getNamespaceContextPointer()
Returns the namespace context pointer set with
setNamespaceContextPointer()
or, if none has been specified, the context pointer otherwise. |
String |
getNamespaceURI(String prefix)
Given a prefix, returns a registered namespace URI.
|
NodeSet |
getNodeSetByKey(String key,
Object value)
Locates a NodeSet by key/value.
|
JXPathContext |
getParentContext()
Returns the parent context of this context or null.
|
abstract Pointer |
getPointer(String xpath)
Traverses the xpath and returns a Pointer.
|
Pointer |
getPointerByID(String id)
Locates a Node by its ID.
|
Pointer |
getPointerByKey(String key,
String value)
Locates a Node by a key value.
|
String |
getPrefix(String namespaceURI)
Get the prefix associated with the specifed namespace URI.
|
abstract JXPathContext |
getRelativeContext(Pointer pointer)
Returns a JXPathContext that is relative to the current JXPathContext.
|
abstract Object |
getValue(String xpath)
Evaluates the xpath and returns the resulting object.
|
abstract Object |
getValue(String xpath,
Class requiredType)
Evaluates the xpath, converts the result to the specified class and
returns the resulting object.
|
Variables |
getVariables()
Returns the variable pool associated with the context.
|
boolean |
isLenient()
Learn whether this JXPathContext is lenient.
|
abstract Iterator |
iterate(String xpath)
Traverses the xpath and returns an Iterator of all results found
for the path.
|
abstract Iterator |
iteratePointers(String xpath)
Traverses the xpath and returns an Iterator of Pointers.
|
static JXPathContext |
newContext(JXPathContext parentContext,
Object contextBean)
Creates a new JXPathContext with the specified bean as the root node and
the specified parent context.
|
static JXPathContext |
newContext(Object contextBean)
Creates a new JXPathContext with the specified object as the root node.
|
void |
registerNamespace(String prefix,
String namespaceURI)
Registers a namespace prefix.
|
abstract void |
removeAll(String xpath)
Removes all elements of the object graph described by the xpath.
|
abstract void |
removePath(String xpath)
Removes the element of the object graph described by the xpath.
|
List |
selectNodes(String xpath)
Finds all nodes that match the specified XPath.
|
Object |
selectSingleNode(String xpath)
Finds the first object that matches the specified XPath.
|
void |
setDecimalFormatSymbols(String name,
DecimalFormatSymbols symbols)
Sets
DecimalFormatSymbols for a given name. |
void |
setExceptionHandler(ExceptionHandler exceptionHandler)
Set the ExceptionHandler used by this context, if any.
|
void |
setFactory(AbstractFactory factory)
Install an abstract factory that should be used by the
createPath() and createPathAndSetValue()
methods. |
void |
setFunctions(Functions functions)
Install a library of extension functions.
|
void |
setIdentityManager(IdentityManager idManager)
Install an identity manager that will be used by the context
to look up a node by its ID.
|
void |
setKeyManager(KeyManager keyManager)
Install a key manager that will be used by the context
to look up a node by a key value.
|
void |
setLenient(boolean lenient)
If the context is in the lenient mode, then getValue() returns null
for inexistent paths.
|
void |
setLocale(Locale locale)
Set the locale for this context.
|
void |
setNamespaceContextPointer(Pointer namespaceContextPointer)
Namespace prefixes can be defined implicitly by specifying a pointer to a
context where the namespaces are defined.
|
abstract void |
setValue(String xpath,
Object value)
Modifies the value of the property described by the supplied xpath.
|
void |
setVariables(Variables vars)
Installs a custom implementation of the Variables interface.
|
protected JXPathContext parentContext
protected Object contextBean
protected AbstractFactory factory
protected IdentityManager idManager
protected KeyManager keyManager
protected HashMap decimalFormats
protected JXPathContext(JXPathContext parentContext, Object contextBean)
parentContext
- parent contextcontextBean
- Objectpublic static JXPathContext newContext(Object contextBean)
contextBean
- Objectpublic static JXPathContext newContext(JXPathContext parentContext, Object contextBean)
parentContext
- parent contextcontextBean
- Objectpublic JXPathContext getParentContext()
public Object getContextBean()
public abstract Pointer getContextPointer()
public abstract JXPathContext getRelativeContext(Pointer pointer)
pointer
- Pointerpublic void setVariables(Variables vars)
vars
- Variablespublic Variables getVariables()
setVariables(org.apache.commons.jxpath.Variables)
method,
returns the default implementation of Variables,
BasicVariables
.public void setFunctions(Functions functions)
functions
- FunctionsFunctionLibrary
public Functions getFunctions()
public void setFactory(AbstractFactory factory)
createPath()
and createPathAndSetValue()
methods.factory
- AbstractFactorypublic AbstractFactory getFactory()
public void setLocale(Locale locale)
Locale.getDefault()
locale
- Localepublic Locale getLocale()
public void setDecimalFormatSymbols(String name, DecimalFormatSymbols symbols)
DecimalFormatSymbols
for a given name. The DecimalFormatSymbols
can be referenced as the third, optional argument in the invocation of
format-number (number,format,decimal-format-name)
function.
By default, JXPath uses the symbols for the current locale.name
- the format name or null for default format.symbols
- DecimalFormatSymbolspublic DecimalFormatSymbols getDecimalFormatSymbols(String name)
name
- keysetDecimalFormatSymbols(String, DecimalFormatSymbols)
public void setLenient(boolean lenient)
By default, lenient = false
lenient
- flagpublic boolean isLenient()
setLenient(boolean)
public static CompiledExpression compile(String xpath)
xpath
- to compileprotected abstract CompiledExpression compilePath(String xpath)
compile()
.xpath
- to compilepublic Object selectSingleNode(String xpath)
getPointer(xpath).getNode()
. Note that this method
produces the same result as getValue()
on object models
like JavaBeans, but a different result for DOM/JDOM etc., because it
returns the Node itself, rather than its textual contents.xpath
- the xpath to be evaluatedpublic List selectNodes(String xpath)
xpath
- the xpath to be evaluatedpublic abstract Object getValue(String xpath)
xpath
- to evaluatepublic abstract Object getValue(String xpath, Class requiredType)
xpath
- to evaluaterequiredType
- required typepublic abstract void setValue(String xpath, Object value)
xpath
- indicating positionvalue
- to setpublic abstract Pointer createPath(String xpath)
AbstractFactory
,
which should first be installed on the context by calling setFactory(org.apache.commons.jxpath.AbstractFactory)
.
Will throw an exception if the AbstractFactory fails to create an instance for a path element.
xpath
- indicating destination to createpublic abstract Pointer createPathAndSetValue(String xpath, Object value)
AbstractFactory
, which should first be
installed on the context by calling setFactory(org.apache.commons.jxpath.AbstractFactory)
.
Will throw an exception if one of the following conditions occurs:
xpath
- indicating position to createvalue
- to setpublic abstract void removePath(String xpath)
xpath
- indicating position to removepublic abstract void removeAll(String xpath)
xpath
- indicating positions to removepublic abstract Iterator iterate(String xpath)
xpath
- to iteratepublic abstract Pointer getPointer(String xpath)
xpath
- desiredpublic abstract Iterator iteratePointers(String xpath)
xpath
- to iteratepublic void setIdentityManager(IdentityManager idManager)
idManager
- IdentityManager to setpublic IdentityManager getIdentityManager()
public Pointer getPointerByID(String id)
id
- is the ID of the sought node.public void setKeyManager(KeyManager keyManager)
keyManager
- KeyManagerpublic KeyManager getKeyManager()
public Pointer getPointerByKey(String key, String value)
key
- stringvalue
- stringpublic NodeSet getNodeSetByKey(String key, Object value)
key
- stringvalue
- objectpublic void registerNamespace(String prefix, String namespaceURI)
prefix
- A namespace prefixnamespaceURI
- A URI for that prefixpublic String getNamespaceURI(String prefix)
setNamespaceContextPointer
.prefix
- The namespace prefix to look uppublic String getPrefix(String namespaceURI)
namespaceURI
- the ns URI to check.public void setNamespaceContextPointer(Pointer namespaceContextPointer)
getContextPointer()
namespaceContextPointer
- The pointer to the context where prefixes used in
XPath expressions should be resolved.public Pointer getNamespaceContextPointer()
setNamespaceContextPointer()
or, if none has been specified, the context pointer otherwise.public void setExceptionHandler(ExceptionHandler exceptionHandler)
exceptionHandler
- to setCopyright © 2001–2015 The Apache Software Foundation. All rights reserved.