XPath?

Peter Hansen peter at engcorp.com
Mon Apr 15 22:12:48 EDT 2002


Philipp Lenssen wrote:
> 
> Is it possible to use XPath in Python, if so are there any small samples? (I
> already saw some XML DOM and SAX mentioned in the context of Python, but
> little of XPath.) I don't mean using XSLT files, but opening an XML file in
> Python, and executing something like evaluate/ match/
> selectNodes(xPathString), returning a set of nodes.

Try this out for a start:

>>> import xml.dom.minidom
>>> from xml.xpath.Context import Context
>>> import xml.xpath
>>> s = '''<?xml version="1.0"?>
... <root>
... <elem attr="1">Some text</elem>
... <elem attr="2">More text</elem>
... </root>'''
>>> d = xml.dom.minidom.parseString(s)
>>> path = xml.xpath.Compile('//elem[@attr="1"]')
>>> result = path.evaluate(Context(d))
>>> print result
[<DOM Element: elem at 18968128>]
>>> print result[0].nodeName
elem
>>> print result[0].firstChild.nodeValue
Some text

I believe there is a small step or to required to install the latest
PyXML over the standard distribution which has a previous version.
It was documented clearly somewhere, but I don't recall what the
steps were.  (I don't think xpath was in the latest standard release,
but I could remember incorrectly.)

-Peter



More information about the Python-list mailing list