find() method in ElementTree

mirandacascade at yahoo.com mirandacascade at yahoo.com
Sat Oct 22 19:35:34 CEST 2005


I do not understand how to use the find() method in ElementTree.

The file 'sample.xml' is:

<?xml version="1.0"?>
<SampleRoot>
    <Header>
        <Product>FindMystery</Product>
    </Header>
    <SpecificInformation>
        <SampleDetail>abc</SampleDetail>
    </SpecificInformation>
</SampleRoot>

>>> from elementtree.ElementTree import ElementTree
>>> doc = ElementTree(file='sample.xml')
>>> iterList = doc.getiterator()
>>> iterList
[<Element SampleRoot at 1166850>, <Element Header at 1166878>, <Element
Product at 11668a0>, <Element SpecificInformation at 1166940>, <Element
SampleDetail at 1166990>]
>>> len(iterList)
5
>>> element = iterList[4]
>>> element.tag
'SampleDetail'
>>> x = doc.find('SampleDetail')
>>> if x == None:
... 	print 'x is none'
...
x is none
>>>

The ElementTree documentation indicates that:
"find(pattern) returns the first subelement that matches the given
pattern, or None if there is no matching element."

and

"the pattern argument can either be a tag name, or a path expression"

Based on the following snippet from the interactive window:

>>> doc = ElementTree(file='sample.xml')
>>> iterList = doc.getiterator()
>>> element = iterList[4]
>>> element.tag
'SampleDetail'

I inferred (perhaps incorrectly) that within doc there is a subelement
with a tag 'SampleDetail'.

Based on the following snippet:

>>> x = doc.find('SampleDetail')
>>> if x == None:
... 	print 'x is none'
...
x is none

I conclude that there is no subelement in doc with a tag
'SampleDetails'.

My questions:
1) in the example above is there a subelement of doc with a tag
'SampleDetails'?
2) if so, what is the proper way of writing the call to the find()
method to locate that subelement?




More information about the Python-list mailing list