Using XPath expressions on an XML document with namespaces

February 17 2012

3 comments 0
motif

The other day I helped a customer figure out a little problem: they had an document and wanted to process it depending on an XPath expression. Here’s the Mule config that shows what we were trying to achieve:

Running XML documents through this config did not work: none of the when expressions matched and we always got the log output for the otherwise case. Let me show you an XML document that’s similar to the one the customer had. I’m using Google’s checkout XML as an example:

The one thing that’s a bit special about this XML document is that it declares a default namespace. Is it possible that this namespace causes trouble? Running an XML document without default namespace declaration through the Mule config above, the XPath expressions match.

I learned a bit more about XPath expressions and found that the expressions used above only match on elements that do not have a namespace declared. So the XPath expression must prefix each element with a proper namespace to match.

But how can we accomplish this? In contrast to Mule’s XML documents, where the namespace has a proper prefix declared, we don’t have any prefix here. Mule’s namespace manager to the rescue! It allows you to declare a prefix and bind it to a namespace. Have a look at the updated config that delcares the prefix “gco” for the default namespace that’s used in the XML document. Also note how the XPath expressions use the prefix now.

If you want to see this example in action or play with it some more, check it out on github.


We'd love to hear your opinion on this post


3 Responses to “Using XPath expressions on an XML document with namespaces”

  1. Am curious why “when & otherwise” instead of “if & else”.

  2. Thank you, namespace-manager helps me!!! . It’s located in the mule namespace http://www.mulesoft.org/schema/mule/xml

  3. Hi good blog, can you suggest how can we put dynamic value in an xpath expression like i have a variable in mule

    and i want it to be used it in

    so instead of UPS can i put productIdvar value dynamically?
    And how to achieve that
    Thanks