import sys
import re
import os.path

def file2DOM(filename):
    reader = Sax2.Reader()
    doc = reader.fromStream(filename)
    return doc

def get_from(dom, xpath_expr):
    match = xpath.Evaluate(xpath_expr, dom)
    if match:
        return match[0].nodeValue
    else:
        raise Exception("No %s in the DOM tree" % xpath)

if len(sys.argv) < 3:
    raise Exception("Usage: %s xpath file" % sys.argv[0])
xpath_text = sys.argv[1]
filename = sys.argv[2]
# TODO: the name of the cache should depend on the XPath expression!
filecachename = re.sub("\.[^\.]+$", ".xpath-cache", filename)
if os.path.exists (filecachename): # TODO: may be we should check its creation time
    # as well, to be sure it is newer than filename? Or we could rely on "make" to
    # do so.
    result = open(filecachename).read()
else:
    from xml.dom.ext.reader import Sax2
    from xml import xpath
    file_dom = file2DOM(filename)
    result = get_from(file_dom, xpath_text)
    cache = open(filecachename, "w")
    cache.write("%s" % result)
    cache.close()
print result


