You can use xpath("
to
evaluate an XPath expression on the current exchange (where the XPath expression is
applied to the body of the current In message). The result of
the Expression
")xpath()
expression is an XML node (or node set, if more than one
node matches).
For example, to extract the contents of the /person/name
element from
the current In message body and use it to set a header named
user
, you could define a route like the following:
from("queue:foo") .setHeader("user", xpath("/person/name/text()")) .to("direct:tie");
Instead of specifying xpath()
as an argument to
setHeader()
, you can use the fluent builder xpath()
command—for example:
from("queue:foo") .setHeader("user").xpath("/person/name/text()") .to("direct:tie");
If you want to convert the result to a specific type, specify the result type as
the second argument of xpath()
. For example, to specify explicitly that
the result type is String
:
xpath("/person/name/text()", String.class)
Typically, XML elements belong to a schema, which is identified by a namespace
URI. When processing documents like this, it is necessary to associate namespace
URIs with prefixes, so that you can identify element names unambiguously in your
XPath expressions. Fuse Mediation Router provides the helper class,
org.apache.camel.builder.xml.Namespaces
, which enables you to
define associations between namespaces and prefixes.
For example, to associate the prefix, cust
, with the namespace,
http://acme.com/customer/record
, and then extract the contents of
the element, /cust:person/cust:name
, you could define a route like the
following:
import org.apache.camel.builder.xml.Namespaces;
...
Namespaces ns = new Namespaces("cust", "http://acme.com/customer/record");
from("queue:foo")
.setHeader("user", xpath("/cust:person/cust:name/text()", ns))
.to("direct:tie");
Where you make the namespace definitions available to the xpath()
expression builder by passing the Namespaces
object, ns
,
as an additional argument. If you need to define multiple namespaces, use the
Namespace.add()
method, as follows:
import org.apache.camel.builder.xml.Namespaces; ... Namespaces ns = new Namespaces("cust", "http://acme.com/customer/record"); ns.add("inv", "http://acme.com/invoice"); ns.add("xsi", "http://www.w3.org/2001/XMLSchema-instance");
If you need to specify the result type and define namespaces,
you can use the three-argument form of xpath()
, as follows:
xpath("/person/name/text()", String.class, ns)