xmlstarlet: how to deal with a default namespace in XPath expressions?

I ran into this problem, when I tried to extract values from JasperReport’s JRXML using xmlstarlet. JRXML files introduce a default namespace (which does not seem to serve a lot), and XPath processors need to take that into account.

When I searched for help in xmlstarlet’s documentation and on the web, I came across this very helpful article:

Once your XML has a default namespace, you have to use that default namespace with every node (that has no explicit namespace part) in your XPath expressions.

As the article above explains, for “xml sel” each such node …

  • … either needs to make use of “_” as name of the default namespace:
# TBD: use a true JasperReports example!

$ xml sel -t -v '/_:publications/_:magazine' 2-023_node-sets.xml
  • or you assign an explicit name (let’s say “a”) to your default namespace on your xmlstarlet command line, and then you have to make use of that “explicit default namespace”:
# TBD: use a true JasperReports example!

$ xml sel -N a:'http://jasperreports.sourceforge.net/jasperreports' -t -v '/a:publications/a:magazine' 2-023_node-sets.xml

CAVEAT: The XPath expressions created by “xml el” do not deal with a default namespace, so you have to adapt them yourself in one of the ways explained above.

A one-liner (e.g. in Perl) can help:

$ xml el FILE.xml | fgrep /subreportExpression |
perl -n -a -F'///' -e 'print "_:",join("/_:",@F)'

Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.