movie rental

in my toolbox

Filed under: Blogroll, python, tech, xpath — Wrote by Otu on Monday, May 7th, 2007 @ 4:16 pm

I hear a lot of people say “I hope I never have to look at another raw XML file again”. For some reason, this comment always make me smile. Mostly because while I see what they mean by it, I love working with XML and given the myriad tools available for manipulating, transforming and processing them, I don’t see myself stopping any time soon.

Recently I needed to evaluate an xpath expression against a bunch of files I had. There are lots of different ways to do this, but they all mostly involved me using some IDE or writing some XSLT file to do this. None of this suited my purpose so I decided to add another tool to my ad-hoc scripts which live in

~/bin

Below is the python script which will evaluate any xpath I pass to it and print out the result on the terminal.

#!/usr/bin/env python
import sys
from xml import xpath
from xml.dom import minidom
from os import path

if len(sys.argv) < 3:
    print "Usage:\n\n%s source-xml-document path-to-evaluate" % path.basename(sys.argv[0])
    sys.exit(0)

source, request = str(path.abspath(sys.argv[1])), str(sys.argv[2])
doc = minidom.parse(source)
results = xpath.Evaluate(request, doc)
print "Result of Evaluation"
print "--------------------\n"
print "Source document '%s'" % source
print "Evaluated'%s'" % request
print "--------------------\n"
print "\n".join([x.toxml() for x in results])
print "--------------------\n"
print "Count: [%s]" % len(results)

An example usage is shown below:

xpath.py topartists.xml "//artist"

Note:
This is in no way exhaustive. For instance, I have made the assumption that the returned result is a list. Clearly not always true, but for my intents at the time, very suitable. Modify for your purpose if you find this useful.

  -

No comments yet. Be the first to comment this post.

Leave your comment

You must be logged in to post a comment.

Formation SAGE © il maestro ignoto