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=

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

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

Quite a handy little tool.


  1. I know wrong platform, but Power Shell would enable you to do that as well. For next time ;)

  2. Cool thanks! Sad that powershell doesn't ship with Vista.

  3. Oh by the way Mark, if you can tell me how to easily set namespaces in the XPath context and execute the XPath from powershell, let me know.. :) I would prefer not to program a real script in powershell, which is probably what you meant. I just wanted a command line tool, and yes, with powershell you can get to the .NET Framework so it is possible to use System.Xml and all that, but probably not as easy as two lines. Try to do a count of elements within a soap Envelope with all the namespaces declared and you will see what I mean.