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 '[EMAIL PROTECTED]'[EMAIL PROTECTED]']'
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='[EMAIL PROTECTED]' name='Mr. Jones'/>
<mail:Subject>just a note</mail:Subject>
<mail:To>
    <mail:mailto address='[EMAIL PROTECTED]' name='Mrs Jones' test='3' />
    <mail:mailto address='[EMAIL PROTECTED]' name='Mr Smith' test='1'/>
</mail:To>
<mail:To>
    <mail:mailto address='[EMAIL PROTECTED]' 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/[EMAIL PROTECTED]'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/[EMAIL PROTECTED]<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)

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to