Home RSS feed


XPath shell script

I often want to quickly run an XPath expression against an XML file, e.g. when grep is not satisfactory. Commands I have tried usually don't even support "*:name" to ignore namespaces. I wrote a script based on xsltproc that ignores all namespaces, selects nodes matched, and prints an optionally customized expression for each node:


Name spaces are ignored. For each node matched by the first
expression, the optional expression (default: ".") is applied.

Example: xpath file "/books/book[year=1983]" "concat(title,author)"

The output consists of two columns; the path to the matched node, and the value of the matched node (the 2nd expression). Example:

$ xpath pom.xml //version
/project/version        0.2
/project/build/plugins/plugin[1]/version        3.1
/project/build/plugins/plugin[2]/version        2.6

I also wrote a completion script to enable auto completion of XPath expressions, like:

$ xpath pom.xml /project/de[TAB][TAB]
/project/dependencies/  /project/developers/

The files: xpath.sh, xpath_completion.

Tags: bash

Created on Sat, 12 Apr 2014 23:00

blog comments powered by Disqus