wp.jochen.hayek.name/blog-en

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 …

# TBD: use a true JasperReports example!

$ xml sel -t -v '/_:publications/_:magazine' 2-023_node-sets.xml
# 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)'
Exit mobile version