Friday, October 16, 2009

Executing XPath from the command line

I had to check some large (SOAP) XML files the other day and was wondering if there was an easy command line tool to execute XPath expressions. I found xmllint in my Cygwin install, and it happened to be installed on the linux servers I was working on.

It's actually quite easy to use:
xmllint --noent --shell file.xml

That opens up a shell in which you can do many things, but at the time I was only interested in running some XPath expressions. The first thing you run into is that namespaces can get in your way with XPath. You need to register the namespaces in the XML to prefixes that can be used in the XPath context.
In the shell you can use this command to for instance register soap:
/ > setns soap=http://schemas.xmlsoap.org/soap/envelope/

after that you can run xpath expressions, some simple examples:

/ > xpath soap:Envelope
/ > xpath count(//mynamespace:myElement)

Quite a handy little tool.