XPath-like filtering for ElementTree

Gerard Flanagan grflanagan at yahoo.co.uk
Mon Dec 26 18:42:56 EST 2005


Pseudo-XPath support for ElementTree with the emphasis on 'Pseudo'.

    http://gflanagan.net/site/python/pagliacci/ElementFilter.html

It's an approach suggested by the Specification Pattern

    eg. http://www.martinfowler.com/apsupp/spec.pdf

Not tested beyond what follows (no time for more at the minute).

Criticisms and suggestions are welcome.

(one possibly obvious 'feature' is that '[@mail=='name at mail.org']'
won't work, ie. if the name of an attribute is contained within a query
string, and is preceded by an '@' character)

Gerard

xml_test ='''
<mail:Mail  xmlns:mail="xmlns1">
<mail:Date>10/10/05</mail:Date>
<mail:From address='me at org.org' name='Mr. Jones'/>
<mail:Subject>just a note</mail:Subject>
<mail:To>
    <mail:mailto address='you at org.org' name='Mrs Jones' test='3' />
    <mail:mailto address='a.nother at org.org' name='Mr Smith' test='1'/>
</mail:To>
<mail:To>
    <mail:mailto address='you at org.org' name='Mrs Jones' test='2'/>
</mail:To>
<mail:Cc></mail:Cc>
<mail:Body>hi there,
just a note to say hi there!</mail:Body>
<mail:Attachments></mail:Attachments>
</mail:Mail>
'''

if __name__ == '__main__':
    print '##########'
    from elementtree import ElementTree
    from elementtree.ElementTree import dump
    root = ElementTree.fromstring( xml_test )
    ns = "xmlns1"
    path = r"{%s}To/{%s}mailto[@name=='Mrs Jones' and @test==3]" %
(ns,ns)
    filter = ElementFilter(path)
    print filter.path
    nodeset1 = filter.findall( root )
    for node in nodeset1:
        dump(node)
    print '-'*30
    filter.path = r"{%s}To/{%s}mailto[@test<3]" % (ns,ns)
    print filter.path
    nodeset2 = filter.findall( root )
    for node in nodeset2:
        dump(node)
    print '-'*30
    assert nodeset1 != nodeset2
    assert filter.findall( root ) != []
    filter.removeall( root )
    assert filter.findall( root ) == []
    dump(root)




More information about the Python-list mailing list