77.9. 使用命名空间
如果您有一个标准的命名空间集,并且希望在多个 XPath 表达式之间共享它们,您可以在使用 Java DSL 时使用 org.apache.camel.support.builder.Namespaces,如下所示:
Namespaces ns = new Namespaces("c", "http://acme.com/cheese");
from("direct:start")
.filter(xpath("/c:person[@name='James']", ns))
.to("mock:result");
Namespaces ns = new Namespaces("c", "http://acme.com/cheese");
from("direct:start")
.filter(xpath("/c:person[@name='James']", ns))
.to("mock:result");
注意如何将命名空间提供给 xquery 以及作为第二参数传递的 ns 变量。
每个命名空间都是 key=value 对,前缀是键。在 XPath 表达式中,命名空间被前缀使用,例如:
/c:person[@name='James']
/c:person[@name='James']
命名空间构建器支持添加多个命名空间,如下所示:
Namespaces ns = new Namespaces("c", "http://acme.com/cheese")
.add("w", "http://acme.com/wine")
.add("b", "http://acme.com/beer");
Namespaces ns = new Namespaces("c", "http://acme.com/cheese")
.add("w", "http://acme.com/wine")
.add("b", "http://acme.com/beer");
在 XML DSL 中使用命名空间时,如您在 XML root 标签中设置命名空间(或 camelContext, routes, route tag 之一)。
在下面的 XML 示例中,我们使用 Spring XML,其中在 root 标签 Bean 中声明命名空间,在 xmlns:foo="http://example.com/person" 一行中:
这个命名空间使用 foo 作为前缀,因此 <xpath> 表达式使用 /foo: 来使用这个命名空间。