find() method in ElementTree

M

mirandacascade

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>
[<Element SampleRoot at 1166850>, <Element Header at 1166878>, <Element
<Element said:
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:
.... 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?
 
F

Fredrik Lundh

My questions:
1) in the example above is there a subelement of doc with a tag
'SampleDetails'?

find only searches for direct subelements; SampleDetail is not a direct
subelement to SampleRoot, since there's a SpecificInformation element
in between.
2) if so, what is the proper way of writing the call to the find()
method to locate that subelement?

elem = doc.find(".//SampleDetail")

should work.

</F>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,226
Members
46,815
Latest member
treekmostly22

Latest Threads

Top