execute an XPath and get the line numbers

I'm investigating the structure of an XML file. The best tool is an usual text editor (vim), but I need to look at some specific tags in some specific contexts. The idea is to execute an XPath and somehow to get to the location in the editor. Remembering that I saw something interesting while playing with libxml internals, I re-checked... And bingo! I've written a script which executes an XPath and prints the result together with the line number of the source XML file.

Usage:

python xpath.py document xpath

Code:

import sys,libxml2

doc_name = sys.argv[1]
xpath    = sys.argv[2]

print doc_name, xpath
doc  = libxml2.parseFile(doc_name)
ctxt = doc.xpathNewContext()
res  = ctxt.xpathEval(xpath)
for node in res:
  print node.lineNo()
  print node

doc.freeDoc()
ctxt.xpathFreeContext()
del ctxt
del doc
Categories: python

Updated: