camel-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Claus Ibsen (Confluence)" <conflue...@apache.org>
Subject [CONF] Apache Camel > XPath
Date Thu, 27 Jun 2013 07:29:00 GMT
<html>
<head>
    <base href="https://cwiki.apache.org/confluence">
            <link rel="stylesheet" href="/confluence/s/en/2176/1/1/_/styles/combined.css?spaceKey=CAMEL&amp;forWysiwyg=true"
type="text/css">
    </head>
<body style="background: white;" bgcolor="white" class="email-body">
<div id="pageContent">
<div id="notificationFormat">
<div class="wiki-content">
<div class="email">
    <h2><a href="https://cwiki.apache.org/confluence/display/CAMEL/XPath">XPath</a></h2>
    <h4>Page <b>edited</b> by             <a href="https://cwiki.apache.org/confluence/display/~davsclaus">Claus
Ibsen</a>
    </h4>
        <br/>
                         <h4>Changes (1)</h4>
                                 
    
<div id="page-diffs">
                    <table class="diff" cellpadding="0" cellspacing="0">
    
            <tr><td class="diff-snipped" >...<br></td></tr>
            <tr><td class="diff-unchanged" >Camel supports [XPath|http://www.w3.org/TR/xpath]
to allow an [Expression] or [Predicate] to be used in the [DSL] or [Xml Configuration]. For
example you could use XPath to create an [Predicate] in a [Message Filter] or as an [Expression]
for a [Recipient List]. <br> <br></td></tr>
            <tr><td class="diff-added-lines" style="background-color: #dfd;">{info:title=Streams}
<br>If the message body is stream based, which means the input it receives is submitted
to Camel as a stream. That means you will only be able to read the content of the stream *once*.
So often when you use [XPath] as [Message Filter] or [Content Based Router] then you need
to access the data multiple times, and you should use [Stream Caching] or convert the message
body to a {{String}} prior which is safe to be re-read multiple times. <br>{info} <br>
<br></td></tr>
            <tr><td class="diff-unchanged" >{code} <br>from(&quot;queue:foo&quot;).
<br></td></tr>
            <tr><td class="diff-snipped" >...<br></td></tr>
    
            </table>
    </div>                            <h4>Full Content</h4>
                    <div class="notificationGreySide">
        <h2><a name="XPath-XPath"></a>XPath</h2>

<p>Camel supports <a href="http://www.w3.org/TR/xpath" class="external-link" rel="nofollow">XPath</a>
to allow an <a href="/confluence/display/CAMEL/Expression" title="Expression">Expression</a>
or <a href="/confluence/display/CAMEL/Predicate" title="Predicate">Predicate</a>
to be used in the <a href="/confluence/display/CAMEL/DSL" title="DSL">DSL</a>
or <a href="/confluence/display/CAMEL/Xml+Configuration" title="Xml Configuration">Xml
Configuration</a>. For example you could use XPath to create an <a href="/confluence/display/CAMEL/Predicate"
title="Predicate">Predicate</a> in a <a href="/confluence/display/CAMEL/Message+Filter"
title="Message Filter">Message Filter</a> or as an <a href="/confluence/display/CAMEL/Expression"
title="Expression">Expression</a> for a <a href="/confluence/display/CAMEL/Recipient+List"
title="Recipient List">Recipient List</a>.</p>

<div class='panelMacro'><table class='infoMacro'><colgroup><col width='24'><col></colgroup><tr><td
valign='top'><img src="/confluence/images/icons/emoticons/information.gif" width="16"
height="16" align="absmiddle" alt="" border="0"></td><td><b>Streams</b><br
/>If the message body is stream based, which means the input it receives is submitted to
Camel as a stream. That means you will only be able to read the content of the stream <b>once</b>.
So often when you use <a href="/confluence/display/CAMEL/XPath" title="XPath">XPath</a>
as <a href="/confluence/display/CAMEL/Message+Filter" title="Message Filter">Message
Filter</a> or <a href="/confluence/display/CAMEL/Content+Based+Router" title="Content
Based Router">Content Based Router</a> then you need to access the data multiple
times, and you should use <a href="/confluence/display/CAMEL/Stream+caching" title="Stream
caching">Stream caching</a> or convert the message body to a <tt>String</tt>
prior which is safe to be re-read multiple times.</td></tr></table></div>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family:
ConfluenceInstalledFont,monospace;">
from("queue:foo").
  filter().xpath("//foo")).
  to("queue:bar")
</pre>
</div></div>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family:
ConfluenceInstalledFont,monospace;">
from("queue:foo").
  choice().xpath("//foo")).to("queue:bar").
  otherwise().to("queue:others");
</pre>
</div></div>

<h3><a name="XPath-Namespaces"></a>Namespaces</h3>

<p>You can easily use namespaces with XPath expressions using the Namespaces helper
class.</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<script type="syntaxhighlighter" class="theme: Default; brush: java; gutter: false"><![CDATA[
Namespaces ns = new Namespaces("c", "http://acme.com/cheese");

from("direct:start").filter().
        xpath("/c:person[@name='James']", ns).
        to("mock:result");
]]></script>
</div></div>

<h3><a name="XPath-Variables"></a>Variables</h3>

<p>Variables in XPath is defined in different namespaces. The default namespace is <tt><a
href="http://camel.apache.org/schema/spring" class="external-link" rel="nofollow">http://camel.apache.org/schema/spring</a></tt>.</p>

<div class='table-wrap'>
<table class='confluenceTable'><tbody>
<tr>
<th class='confluenceTh'> Namespace URI </th>
<th class='confluenceTh'> Local part </th>
<th class='confluenceTh'> Type </th>
<th class='confluenceTh'> Description </th>
</tr>
<tr>
<td class='confluenceTd'> <a href="http://camel.apache.org/xml/in/" class="external-link"
rel="nofollow">http://camel.apache.org/xml/in/</a> </td>
<td class='confluenceTd'> in </td>
<td class='confluenceTd'> Message </td>
<td class='confluenceTd'> the exchange.in message </td>
</tr>
<tr>
<td class='confluenceTd'> <a href="http://camel.apache.org/xml/out/" class="external-link"
rel="nofollow">http://camel.apache.org/xml/out/</a> </td>
<td class='confluenceTd'>  out </td>
<td class='confluenceTd'> Message </td>
<td class='confluenceTd'> the exchange.out message </td>
</tr>
<tr>
<td class='confluenceTd'> <a href="http://camel.apache.org/xml/function/" class="external-link"
rel="nofollow">http://camel.apache.org/xml/function/</a> </td>
<td class='confluenceTd'> functions </td>
<td class='confluenceTd'> Object </td>
<td class='confluenceTd'> <b>Camel 2.5:</b> Additional functions </td>
</tr>
<tr>
<td class='confluenceTd'> <a href="http://camel.apache.org/xml/variables/environment-variables"
class="external-link" rel="nofollow">http://camel.apache.org/xml/variables/environment-variables</a>
</td>
<td class='confluenceTd'> env </td>
<td class='confluenceTd'> Object </td>
<td class='confluenceTd'> OS environment variables </td>
</tr>
<tr>
<td class='confluenceTd'> <a href="http://camel.apache.org/xml/variables/system-properties"
class="external-link" rel="nofollow">http://camel.apache.org/xml/variables/system-properties</a>
</td>
<td class='confluenceTd'> system </td>
<td class='confluenceTd'> Object </td>
<td class='confluenceTd'> Java System properties </td>
</tr>
<tr>
<td class='confluenceTd'> <a href="http://camel.apache.org/xml/variables/exchange-property"
class="external-link" rel="nofollow">http://camel.apache.org/xml/variables/exchange-property</a>
</td>
<td class='confluenceTd'>&nbsp;</td>
<td class='confluenceTd'> Object </td>
<td class='confluenceTd'> the exchange property </td>
</tr>
</tbody></table>
</div>


<p>Camel will resolve variables according to either:</p>
<ul class="alternate" type="square">
	<li>namespace given</li>
	<li>no namespace given</li>
</ul>


<h4><a name="XPath-Namespacegiven"></a>Namespace given</h4>
<p>If the namespace is given then Camel is instructed exactly what to return. However
when resolving either <b>in</b> or <b>out</b> Camel will try to resolve
a header with the given local part first, and return it. If the local part has the value <b>body</b>
then the body is returned instead. </p>

<h4><a name="XPath-Nonamespacegiven"></a>No namespace given</h4>
<p>If there is no namespace given then Camel resolves only based on the local part.
Camel will try to resolve a variable in the following steps:</p>
<ul class="alternate" type="square">
	<li>from <tt>variables</tt> that has been set using the <tt>variable(name,
value)</tt> fluent builder</li>
	<li>from message.in.header if there is a header with the given key</li>
	<li>from exchange.properties if there is a property with the given key</li>
</ul>


<h3><a name="XPath-Functions"></a>Functions</h3>
<p>Camel adds the following XPath functions that can be used to access the exchange:</p>

<div class='table-wrap'>
<table class='confluenceTable'><tbody>
<tr>
<th class='confluenceTh'> Function </th>
<th class='confluenceTh'> Argument </th>
<th class='confluenceTh'> Type </th>
<th class='confluenceTh'> Description </th>
</tr>
<tr>
<td class='confluenceTd'> in:body </td>
<td class='confluenceTd'> none </td>
<td class='confluenceTd'> Object </td>
<td class='confluenceTd'> Will return the <b>in</b> message body. </td>
</tr>
<tr>
<td class='confluenceTd'> in:header </td>
<td class='confluenceTd'> the header name </td>
<td class='confluenceTd'> Object </td>
<td class='confluenceTd'> Will return the <b>in</b> message header. </td>
</tr>
<tr>
<td class='confluenceTd'> out:body </td>
<td class='confluenceTd'> none </td>
<td class='confluenceTd'> Object </td>
<td class='confluenceTd'> Will return the <b>out</b> message body. </td>
</tr>
<tr>
<td class='confluenceTd'> out:header </td>
<td class='confluenceTd'> the header name </td>
<td class='confluenceTd'> Object </td>
<td class='confluenceTd'> Will return the <b>out</b> message header. </td>
</tr>
<tr>
<td class='confluenceTd'> function:properties </td>
<td class='confluenceTd'> key for property </td>
<td class='confluenceTd'> String </td>
<td class='confluenceTd'> <b>Camel 2.5:</b> To lookup a property using the
<a href="/confluence/display/CAMEL/Properties" title="Properties">Properties</a>
component (property placeholders). </td>
</tr>
<tr>
<td class='confluenceTd'> function:simple </td>
<td class='confluenceTd'> simple expression </td>
<td class='confluenceTd'> Object </td>
<td class='confluenceTd'> <b>Camel 2.5:</b> To evaluate a <a href="/confluence/display/CAMEL/Simple"
title="Simple">Simple</a> expression. </td>
</tr>
</tbody></table>
</div>


<p><b>Notice:</b> <tt>function:properties</tt> and <tt>function:simple</tt>
is not supported when the return type is a <tt>NodeSet</tt>, such as when using
with a <a href="/confluence/display/CAMEL/Splitter" title="Splitter">Splitter</a>
EIP.</p>

<p>Here's an example showing some of these functions in use.</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<script type="syntaxhighlighter" class="theme: Default; brush: java; gutter: false"><![CDATA[
from("direct:start").choice()
  .when().xpath("in:header('foo') = 'bar'").to("mock:x")
  .when().xpath("in:body() = '&lt;two/&gt;'").to("mock:y")
  .otherwise().to("mock:z");
]]></script>
</div></div>

<p>And the new functions introduced in Camel 2.5:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<script type="syntaxhighlighter" class="theme: Default; brush: java; gutter: false"><![CDATA[
// setup properties component
PropertiesComponent properties = new PropertiesComponent();
properties.setLocation("classpath:org/apache/camel/builder/xml/myprop.properties");
context.addComponent("properties", properties);

// myprop.properties contains the following properties
// foo=Camel
// bar=Kong

from("direct:in").choice()
    // $type is a variable for the header with key type
    // here we use the properties function to lookup foo from the properties files
    // which at runtime will be evaluted to 'Camel'
    .when().xpath("$type = function:properties('foo')")
        .to("mock:camel")
    // here we use the simple language to evaluate the expression
    // which at runtime will be evaluated to 'Donkey Kong'
    .when().xpath("//name = function:simple('Donkey ${properties:bar}')")
        .to("mock:donkey")
    .otherwise()
        .to("mock:other")
    .end();
]]></script>
</div></div>


<h3><a name="XPath-UsingXMLconfiguration"></a>Using XML configuration</h3>

<p>If you prefer to configure your routes in your <a href="/confluence/display/CAMEL/Spring"
title="Spring">Spring</a> XML file then you can use XPath expressions as follows</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: xml; gutter: false" style="font-size:12px; font-family:
ConfluenceInstalledFont,monospace;">
&lt;beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd"&gt;

  &lt;camelContext id="camel" xmlns="http://activemq.apache.org/camel/schema/spring" xmlns:foo="http://example.com/person"&gt;
    &lt;route&gt;
      &lt;from uri="activemq:MyQueue"/&gt;
      &lt;filter&gt;
        &lt;xpath&gt;/foo:person[@name='James']&lt;/xpath&gt;
        &lt;to uri="mqseries:SomeOtherQueue"/&gt;
      &lt;/filter&gt;
    &lt;/route&gt;
  &lt;/camelContext&gt;
&lt;/beans&gt;
</pre>
</div></div>

<p>Notice how we can reuse the namespace prefixes, <b>foo</b> in this case,
in the XPath expression for easier namespace based XPath expressions!</p>

<p>See also this <a href="http://camel.465427.n5.nabble.com/fail-filter-XPATH-camel-td476424.html"
class="external-link" rel="nofollow">discussion on the mailinglist</a> about using
your own namespaces with xpath</p>

<h3><a name="XPath-Settingresulttype"></a>Setting result type</h3>
<p>The <a href="/confluence/display/CAMEL/XPath" title="XPath">XPath</a>
expression will return a result type using native XML objects such as <tt>org.w3c.dom.NodeList</tt>.
But many times you want a result type to be a String. To do this you have to instruct the
<a href="/confluence/display/CAMEL/XPath" title="XPath">XPath</a> which result
type to use.</p>

<p>In Java DSL:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family:
ConfluenceInstalledFont,monospace;">
xpath("/foo:person/@id", String.class)
</pre>
</div></div>

<p>In Spring DSL you use the <b>resultType</b> attribute to provide a fully
qualified classname:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: xml; gutter: false" style="font-size:12px; font-family:
ConfluenceInstalledFont,monospace;">
&lt;xpath resultType="java.lang.String"&gt;/foo:person/@id&lt;/xpath&gt;
</pre>
</div></div>

<p>In @XPath:<br/>
<b>Available as of Camel 2.1</b></p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family:
ConfluenceInstalledFont,monospace;">
@XPath(value = "concat('foo-',//order/name/)", resultType = String.class) String name)
</pre>
</div></div>
<p>Where we use the xpath function concat to prefix the order name with <tt>foo-</tt>.
In this case we have to specify that we want a String as result type so the concat function
works.</p>

<h3><a name="XPath-UsingXPathonHeaders"></a>Using XPath on Headers</h3>
<p><b>Available as of Camel 2.11</b></p>

<p>Some users may have XML stored in a header. To apply an XPath to a header's value
you can do this by defining the 'headerName' attribute.</p>

<p>In XML DSL:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<script type="syntaxhighlighter" class="theme: Default; brush: xml; gutter: false"><![CDATA[
&lt;camelContext id="xpathHeaderNameTest" xmlns="http://camel.apache.org/schema/blueprint"&gt;
  &lt;route&gt;
    &lt;from uri="direct:in"/&gt;
    &lt;choice&gt;
      &lt;when&gt;
        &lt;!-- use headerName attribute to refer to a header --&gt;
        &lt;xpath headerName="invoiceDetails"&gt;/invoice/@orderType = 'premium'&lt;/xpath&gt;
        &lt;to uri="mock:premium"/&gt;
      &lt;/when&gt;
      &lt;when&gt;
        &lt;!-- use headerName attribute to refer to a header --&gt;
        &lt;xpath headerName="invoiceDetails"&gt;/invoice/@orderType = 'standard'&lt;/xpath&gt;
        &lt;to uri="mock:standard"/&gt;
      &lt;/when&gt;
      &lt;otherwise&gt;
        &lt;to uri="mock:unknown"/&gt;
      &lt;/otherwise&gt;
    &lt;/choice&gt;
  &lt;/route&gt;
&lt;/camelContext&gt;
]]></script>
</div></div>

<h3><a name="XPath-Examples"></a>Examples</h3>

<p>Here is a simple <a href="http://svn.apache.org/repos/asf/camel/trunk/camel-core/src/test/java/org/apache/camel/processor/XPathFilterTest.java"
class="external-link" rel="nofollow">example</a> using an XPath expression as a predicate
in a <a href="/confluence/display/CAMEL/Message+Filter" title="Message Filter">Message
Filter</a></p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<script type="syntaxhighlighter" class="theme: Default; brush: java; gutter: false"><![CDATA[
from("direct:start").
        filter().xpath("/person[@name='James']").
        to("mock:result");
]]></script>
</div></div>

<p>If you have a standard set of namespaces you wish to work with and wish to share
them across many different XPath expressions you can use the NamespaceBuilder as shown <a
href="http://svn.apache.org/repos/asf/camel/trunk/camel-core/src/test/java/org/apache/camel/processor/XPathWithNamespaceBuilderFilterTest.java"
class="external-link" rel="nofollow">in this example</a></p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<script type="syntaxhighlighter" class="theme: Default; brush: java; gutter: false"><![CDATA[
// lets define the namespaces we'll need in our filters
Namespaces ns = new Namespaces("c", "http://acme.com/cheese")
        .add("xsd", "http://www.w3.org/2001/XMLSchema");

// now lets create an xpath based Message Filter
from("direct:start").
        filter(ns.xpath("/c:person[@name='James']")).
        to("mock:result");
]]></script>
</div></div>

<p>In this sample we have a choice construct. The first choice evaulates if the message
has a header key <b>type</b> that has the value <b>Camel</b>.<br/>
The 2nd choice evaluates if the message body has a name tag <b>&lt;name&gt;</b>
which values is <b>Kong</b>.<br/>
If neither is true the message is routed in the otherwise block:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<script type="syntaxhighlighter" class="theme: Default; brush: java; gutter: false"><![CDATA[
from("direct:in").choice()
    // using $headerName is special notation in Camel to get the header key
    .when().xpath("$type = 'Camel'")
        .to("mock:camel")
    // here we test for the body name tag
    .when().xpath("//name = 'Kong'")
        .to("mock:donkey")
    .otherwise()
        .to("mock:other")
    .end();
]]></script>
</div></div>

<p>And the spring XML equivalent of the route:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<script type="syntaxhighlighter" class="theme: Default; brush: xml; gutter: false"><![CDATA[
&lt;camelContext xmlns="http://camel.apache.org/schema/spring"&gt;
    &lt;route&gt;
        &lt;from uri="direct:in"/&gt;
        &lt;choice&gt;
            &lt;when&gt;
                &lt;xpath&gt;$type = 'Camel'&lt;/xpath&gt;
                &lt;to uri="mock:camel"/&gt;
            &lt;/when&gt;
            &lt;when&gt;
                &lt;xpath&gt;//name = 'Kong'&lt;/xpath&gt;
                &lt;to uri="mock:donkey"/&gt;
            &lt;/when&gt;
            &lt;otherwise&gt;
                &lt;to uri="mock:other"/&gt;
            &lt;/otherwise&gt;
        &lt;/choice&gt;
    &lt;/route&gt;
&lt;/camelContext&gt;
]]></script>
</div></div>

<h2><a name="XPath-XPathinjection"></a>XPath injection </h2>

<p>You can use <a href="/confluence/display/CAMEL/Bean+Integration" title="Bean Integration">Bean
Integration</a> to invoke a method on a bean and use various languages such as XPath
to extract a value from the message and bind it to a method parameter.</p>

<p>The default XPath annotation has SOAP and XML namespaces available. If you want to
use your own namespace URIs in an XPath expression you can use your own copy of the <a
href="http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/language/XPath.html"
class="external-link" rel="nofollow">XPath annotation</a> to create whatever namespace
prefixes you want to use. </p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<script type="syntaxhighlighter" class="theme: Default; brush: java; gutter: false"><![CDATA[
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.w3c.dom.NodeList;

import org.apache.camel.component.bean.XPathAnnotationExpressionFactory;
import org.apache.camel.language.LanguageAnnotation;
import org.apache.camel.language.NamespacePrefix;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
@LanguageAnnotation(language = "xpath", factory = XPathAnnotationExpressionFactory.class)
public @interface MyXPath {
    String value();

    // You can add the namespaces as the default value of the annotation
    NamespacePrefix[] namespaces() default {
    @NamespacePrefix(prefix = "n1", uri = "http://example.org/ns1"),
    @NamespacePrefix(prefix = "n2", uri = "http://example.org/ns2")};

    Class&lt;?&gt; resultType() default NodeList.class;
}
]]></script>
</div></div>

<p>i.e. cut and paste upper code to your own project in a different package and/or annotation
name then add whatever namespace prefix/uris you want in scope when you use your annotation
on a method parameter. Then when you use your annotation on a method parameter all the namespaces
you want will be available for use in your XPath expression.</p>

<p>For example</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family:
ConfluenceInstalledFont,monospace;">
public class Foo {
	
    @MessageDriven(uri = "activemq:my.queue")
    public void doSomething(@MyXPath("/ns1:foo/ns2:bar/text()") String correlationID, @Body
String body) {
		// process the inbound message here
    }
}
</pre>
</div></div>

<h3><a name="XPath-UsingXPathBuilderwithoutanExchange"></a>Using XPathBuilder
without an Exchange</h3>
<p><b>Available as of Camel 2.3</b></p>

<p>You can now use the <tt>org.apache.camel.builder.XPathBuilder</tt> without
the need for an <a href="/confluence/display/CAMEL/Exchange" title="Exchange">Exchange</a>.
This comes handy if you want to use it as a helper to do custom xpath evaluations. </p>

<p>It requires that you pass in a <a href="/confluence/display/CAMEL/CamelContext"
title="CamelContext">CamelContext</a> since a lot of the moving parts inside the
XPathBuilder requires access to the Camel <a href="/confluence/display/CAMEL/Type+Converter"
title="Type Converter">Type Converter</a> and hence why <a href="/confluence/display/CAMEL/CamelContext"
title="CamelContext">CamelContext</a> is needed.</p>

<p>For example you can do something like this:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family:
ConfluenceInstalledFont,monospace;">
boolean matches = XPathBuilder.xpath("/foo/bar/@xyz").matches(context, "&lt;foo&gt;&lt;bar
xyz='cheese'/&gt;&lt;/foo&gt;"));
</pre>
</div></div>
<p>This will match the given predicate.</p>

<p>You can also evaluate for example as shown in the following three examples:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family:
ConfluenceInstalledFont,monospace;">
    String name = XPathBuilder.xpath("foo/bar").evaluate(context, "&lt;foo&gt;&lt;bar&gt;cheese&lt;/bar&gt;&lt;/foo&gt;",
String.class);
    Integer number = XPathBuilder.xpath("foo/bar").evaluate(context, "&lt;foo&gt;&lt;bar&gt;123&lt;/bar&gt;&lt;/foo&gt;",
Integer.class);
    Boolean bool = XPathBuilder.xpath("foo/bar").evaluate(context, "&lt;foo&gt;&lt;bar&gt;true&lt;/bar&gt;&lt;/foo&gt;",
Boolean.class);
</pre>
</div></div>

<p>Evaluating with a String result is a common requirement and thus you can do it a
bit simpler:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family:
ConfluenceInstalledFont,monospace;">
    String name = XPathBuilder.xpath("foo/bar").evaluate(context, "&lt;foo&gt;&lt;bar&gt;cheese&lt;/bar&gt;&lt;/foo&gt;");
</pre>
</div></div>

<h3><a name="XPath-UsingSaxonwithXPathBuilder"></a>Using Saxon with XPathBuilder</h3>
<p><b>Available as of Camel 2.3</b></p>

<p>You need to add <b>camel-saxon</b> as dependency to your project.</p>

<p>Its now easier to use <a href="http://saxon.sourceforge.net/" class="external-link"
rel="nofollow">Saxon</a> with the XPathBuilder which can be done in several ways
as shown below.<br/>
Where as the latter ones are the easiest ones.</p>

<p>Using a factory</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<script type="syntaxhighlighter" class="theme: Default; brush: java; gutter: false"><![CDATA[
// create a Saxon factory
XPathFactory fac = new net.sf.saxon.xpath.XPathFactoryImpl();

// create a builder to evaluate the xpath using the saxon factory
XPathBuilder builder = XPathBuilder.xpath("tokenize(/foo/bar, '_')[2]").factory(fac);

// evaluate as a String result
String result = builder.evaluate(context, "&lt;foo&gt;&lt;bar&gt;abc_def_ghi&lt;/bar&gt;&lt;/foo&gt;");
assertEquals("def", result);
]]></script>
</div></div>

<p>Using ObjectModel</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<script type="syntaxhighlighter" class="theme: Default; brush: java; gutter: false"><![CDATA[
// create a builder to evaluate the xpath using saxon based on its object model uri
XPathBuilder builder = XPathBuilder.xpath("tokenize(/foo/bar, '_')[2]").objectModel("http://saxon.sf.net/jaxp/xpath/om");

// evaluate as a String result
String result = builder.evaluate(context, "&lt;foo&gt;&lt;bar&gt;abc_def_ghi&lt;/bar&gt;&lt;/foo&gt;");
assertEquals("def", result);
]]></script>
</div></div>

<p>The easy one</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<script type="syntaxhighlighter" class="theme: Default; brush: java; gutter: false"><![CDATA[
// create a builder to evaluate the xpath using saxon
XPathBuilder builder = XPathBuilder.xpath("tokenize(/foo/bar, '_')[2]").saxon();

// evaluate as a String result
String result = builder.evaluate(context, "&lt;foo&gt;&lt;bar&gt;abc_def_ghi&lt;/bar&gt;&lt;/foo&gt;");
assertEquals("def", result);
]]></script>
</div></div>

<h3><a name="XPath-SettingacustomXPathFactoryusingSystemProperty"></a>Setting
a custom XPathFactory using System Property</h3>
<p><b>Available as of Camel 2.3</b></p>

<p>Camel now supports reading the <a href="http://java.sun.com/j2se/1.5.0/docs/api/javax/xml/xpath/XPathFactory.html#newInstance(java.lang.String)"
class="external-link" rel="nofollow">JVM system property <tt>javax.xml.xpath.XPathFactory</tt></a>
that can be used to set a custom XPathFactory to use.</p>

<p>This unit test shows how this can be done to use Saxon instead:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<script type="syntaxhighlighter" class="theme: Default; brush: java; gutter: false"><![CDATA[
// set system property with the XPath factory to use which is Saxon 
System.setProperty(XPathFactory.DEFAULT_PROPERTY_NAME + ":" + "http://saxon.sf.net/jaxp/xpath/om",
"net.sf.saxon.xpath.XPathFactoryImpl");

// create a builder to evaluate the xpath using saxon
XPathBuilder builder = XPathBuilder.xpath("tokenize(/foo/bar, '_')[2]");

// evaluate as a String result
String result = builder.evaluate(context, "&lt;foo&gt;&lt;bar&gt;abc_def_ghi&lt;/bar&gt;&lt;/foo&gt;");
assertEquals("def", result);
]]></script>
</div></div>

<p>Camel will log at <tt>INFO</tt> level if it uses a non default XPathFactory
such as:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family:
ConfluenceInstalledFont,monospace;">
XPathBuilder  INFO  Using system property javax.xml.xpath.XPathFactory:http://saxon.sf.net/jaxp/xpath/om
with value:
                    net.sf.saxon.xpath.XPathFactoryImpl when creating XPathFactory
</pre>
</div></div>

<p>To use Apache Xerces you can configure the system property</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family:
ConfluenceInstalledFont,monospace;">
-Djavax.xml.xpath.XPathFactory=org.apache.xpath.jaxp.XPathFactoryImpl
</pre>
</div></div>

<h3><a name="XPath-EnablingSaxonfromSpringDSL"></a>Enabling Saxon from Spring
DSL</h3>
<p><b>Available as of Camel 2.10</b></p>

<p>Similarly to Java DSL, to enable Saxon from Spring DSL you have three options:</p>

<p>Specifying the factory</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: xml; gutter: false" style="font-size:12px; font-family:
ConfluenceInstalledFont,monospace;">
&lt;xpath factoryRef="saxonFactory" resultType="java.lang.String"&gt;current-dateTime()&lt;/xpath&gt;
</pre>
</div></div>

<p>Specifying the object model</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: xml; gutter: false" style="font-size:12px; font-family:
ConfluenceInstalledFont,monospace;">
&lt;xpath objectModel="http://saxon.sf.net/jaxp/xpath/om" resultType="java.lang.String"&gt;current-dateTime()&lt;/xpath&gt;
</pre>
</div></div>

<p>Shortcut</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: xml; gutter: false" style="font-size:12px; font-family:
ConfluenceInstalledFont,monospace;">
&lt;xpath saxon="true" resultType="java.lang.String"&gt;current-dateTime()&lt;/xpath&gt;
</pre>
</div></div>

<h3><a name="XPath-Namespaceauditingtoaiddebugging"></a>Namespace auditing
to aid debugging</h3>
<p><b>Available as of Camel 2.10</b></p>

<p>A large number of XPath-related issues that users frequently face are linked to the
usage of namespaces. You may have some misalignment between the namespaces present in your
message and those that your XPath expression is aware of or referencing. XPath predicates
or expressions that are unable to locate the XML elements and attributes due to namespaces
issues may simply look like "they are not working", when in reality all there is to it is
a lack of namespace definition.</p>

<p>Namespaces in XML are completely necessary, and while we would love to simplify their
usage by implementing some magic or voodoo to wire namespaces automatically, truth is that
any action down this path would disagree with the standards and would greatly hinder interoperability.</p>

<p>Therefore, the utmost we can do is assist you in debugging such issues by adding
two new features to the XPath Expression Language and are thus accesible from both predicates
and expressions.</p>

<h4><a name="XPath-LoggingtheNamespaceContextofyourXPathexpression%2Fpredicate"></a>Logging
the Namespace Context of your XPath expression/predicate</h4>

<p>Every time a new XPath expression is created in the internal pool, Camel will log
the namespace context of the expression under the <tt>org.apache.camel.builder.xml.XPathBuilder</tt>
logger. Since Camel represents Namespace Contexts in a hierarchical fashion (parent-child
relationships), the entire tree is output in a recursive manner with the following format:</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family:
ConfluenceInstalledFont,monospace;">
[me: {prefix -&gt; namespace}, {prefix -&gt; namespace}], [parent: [me: {prefix -&gt;
namespace}, {prefix -&gt; namespace}], [parent: [me: {prefix -&gt; namespace}]]]
</pre>
</div></div>

<p>Any of these options can be used to activate this logging:</p>
<ol>
	<li>Enable TRACE logging on the <tt>org.apache.camel.builder.xml.XPathBuilder</tt>
logger, or some parent logger such as <tt>org.apache.camel</tt> or the root logger</li>
	<li>Enable the <tt>logNamespaces</tt> option as indicated in <a href="#XPath-AuditingNamespaces">Auditing
Namespaces</a>, in which case the logging will occur on the INFO level</li>
</ol>


<p><a name="XPath-AuditingNamespaces"></a></p>
<h4><a name="XPath-Auditingnamespaces"></a>Auditing namespaces </h4>

<p>Camel is able to discover and dump all namespaces present on every incoming message
before evaluating an XPath expression, providing all the richness of information you need
to help you analyse and pinpoint possible namespace issues. </p>

<p>To achieve this, it in turn internally uses another specially tailored XPath expression
to extract all namespace mappings that appear in the message, displaying the prefix and the
full namespace URI(s) for each individual mapping. </p>

<p>Some points to take into account:</p>

<ul>
	<li>The implicit XML namespace (xmlns:xml="http://www.w3.org/XML/1998/namespace") is
suppressed from the output because it adds no value</li>
	<li>Default namespaces are listed under the DEFAULT keyword in the output</li>
	<li>Keep in mind that namespaces can be remapped under different scopes. Think of a
top-level 'a' prefix which in inner elements can be assigned a different namespace, or the
default namespace changing in inner scopes. For each discovered prefix, all associated URIs
are listed.</li>
</ul>


<p>You can enable this option in Java DSL and Spring DSL.</p>

<p>Java DSL:</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family:
ConfluenceInstalledFont,monospace;">
XPathBuilder.xpath("/foo:person/@id", String.class).logNamespaces()
</pre>
</div></div>

<p>Spring DSL:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: xml; gutter: false" style="font-size:12px; font-family:
ConfluenceInstalledFont,monospace;">
&lt;xpath logNamespaces="true" resultType="String"&gt;/foo:person/@id&lt;/xpath&gt;
</pre>
</div></div>

<p>The result of the auditing will be appear at the INFO level under the <tt>org.apache.camel.builder.xml.XPathBuilder</tt>
logger and will look like the following:</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family:
ConfluenceInstalledFont,monospace;">
2012-01-16 13:23:45,878 [stSaxonWithFlag] INFO  XPathBuilder  - Namespaces discovered in message:

{xmlns:a=[http://apache.org/camel], DEFAULT=[http://apache.org/default], 
xmlns:b=[http://apache.org/camelA, http://apache.org/camelB]}
</pre>
</div></div>

<h3><a name="XPath-Loadingscriptfromexternalresource"></a>Loading script
from external resource</h3>
<p><b>Available as of Camel 2.11</b></p>

<p>You can externalize the script and have Camel load it from a resource such as <tt>"classpath:"</tt>,
<tt>"file:"</tt>, or <tt>"http:"</tt>.<br/>
This is done using the following syntax: <tt>"resource:scheme:location"</tt>,
eg to refer to a file on the classpath you can do:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family:
ConfluenceInstalledFont,monospace;">
.setHeader("myHeader").xpath("resource:classpath:myxpath.txt", String.class)
</pre>
</div></div>

<h3><a name="XPath-Dependencies"></a>Dependencies</h3>
<p>The XPath language is part of camel-core.</p>
    </div>
        <div id="commentsSection" class="wiki-content pageSection">
        <div style="float: right;" class="grey">
                        <a href="https://cwiki.apache.org/confluence/users/removespacenotification.action?spaceKey=CAMEL">Stop
watching space</a>
            <span style="padding: 0px 5px;">|</span>
                <a href="https://cwiki.apache.org/confluence/users/editmyemailsettings.action">Change
email notification preferences</a>
</div>
        <a href="https://cwiki.apache.org/confluence/display/CAMEL/XPath">View Online</a>
        |
        <a href="https://cwiki.apache.org/confluence/pages/diffpagesbyversion.action?pageId=53132&revisedVersion=56&originalVersion=55">View
Changes</a>
                |
        <a href="https://cwiki.apache.org/confluence/display/CAMEL/XPath?showComments=true&amp;showCommentArea=true#addcomment">Add
Comment</a>
            </div>
</div>
</div>
</div>
</div>
</body>
</html>

Mime
View raw message