XPath and XQuery in Python?

John Lenton john at grulic.org.ar
Thu Jan 13 18:39:00 EST 2005


On Wed, Jan 12, 2005 at 12:09:58AM +0000, Nelson Minar wrote:
> Could someone help me get started using XPath or XQuery in Python? I'm
> overwhelmed by all the various options and am lacking guidance on what
> the simplest way to go is. What library do I need to enable three line
> Python programs to extract data with XPath expressions?
> 
> I have this problem a lot with Python and XML. Even with Uche's
> excellent yearly roundups I have a hard time finding how to do fancy
> things with XML in Python. I think it's a bit like web server
> frameworks in Python - too many choices.

my own favorite is libxml2. Something like the following:

    #!/usr/bin/env python
    import libxml2
    import sys

    def grep(what, where):
        doc = libxml2.parseDoc(where)
        for found in doc.xpathEval(what):
            found.saveTo(sys.stdout, format=True)

    if __name__ == '__main__':
        try:
            what = sys.argv[1]
        except IndexError:
            sys.exit("Usage: %s pattern file ..." % sys.argv[0])
        else:
            for where in sys.argv[2:]:
                grep(what, file(where).read())

although you might want to be smarter with the errors...

-- 
John Lenton (john at grulic.org.ar) -- Random fortune:
The whole world is a scab.  The point is to pick it constructively.
		-- Peter Beard
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 196 bytes
Desc: Digital signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20050113/47a71ee3/attachment.sig>


More information about the Python-list mailing list