By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,037 Members | 2,065 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,037 IT Pros & Developers. It's quick & easy.

find() method in ElementTree

P: n/a
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?

Oct 22 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
mi************@yahoo.com wrote:
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>

Oct 22 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.