xml.etree.ElementTree and XPath

Stefan Behnel stefan_ml at behnel.de
Sat Oct 18 15:55:05 EDT 2008


xkenneth wrote:
>     Can I execute XPath queries on ElementTree objects ignoring the
> namespace? IE './node' instead of './{http://namespace.com}node'.

The XPath support in ET is very limited. You can use lxml.etree instead, which
has full support for XPath 1.0, i.e. you can do

    tree.xpath('//*[local-name() = "node"]')

http://codespeak.net/lxml/

Or you can do the iteration yourself, i.e.

    for el in tree.iter(): # or tree.getiterator():
        if isinstance(el.tag, basestring):
            if el.tag.split('}', 1)[-1] == "node":
                print el.tag

which works in both ET and lxml.etree.

Stefan



More information about the Python-list mailing list