What Is Python 2.6 Equivalent Of Iterfind()
Solution 1:
From documentation of xml.etree.ElementTree
-
iter(tag=None)
Creates a tree iterator with the current element as the root. The iterator iterates over this element and all elements below it, in document (depth first) order. If tag is not None or '*', only elements whose tag equals tag are returned from the iterator. If the tree structure is modified during iteration, the result is undefined.
New in version 2.7.
iterfind(match)
Finds all matching subelements, by tag name or path. Returns an iterable yielding all matching elements in document order.
New in version 2.7.
(Emphasis mine)
Just as you noticed, you cannot use iterfind
or iter
in Python 2.7 .
You will have to use findall()
method , to get the data you want. And from my experience, findall()
does not support XPath with predicates (for attributes) in Python 2.6 either. So you would need to get all elements with tag name as success
and then check the attributes of those elements to see if they equal what you want.
Code -
First
>>>import xml.etree.cElementTree as ET>>>tree = ET.ElementTree(file='Test.xml')>>>for elem in tree.findall('.//Pre_EQ/success'):...print elem.tag, elem.attrib, elem.text
Second
>>>for elem in tree.findall('.//success'):...if elem.attrib.get('field_name') == "success":...print elem.tag, elem.attrib, elem.text
Demo -
>>>s='''<?xml version="1.0" encoding="UTF-8"?>...<drum>... <cmts>... <Pre_EQ>... <success field_name="success">1</success>... <coefficient field_name="coefficient">080118000000ffd00000ffe00000fff0001000200020fff000000010002000003fa0000000000020003000000020ffd00010001000000000000000000010000000000020ffc0000000000020000000500010ffe0fff0ffe0ffd0fff0fff0ffd0ffd0fff0</coefficient>... </Pre_EQ>... </cmts>...</drum>'''>>>tree = ET.fromstring(s)>>>for elem in tree.findall('.//Pre_EQ/success'):...print elem.tag, elem.attrib, elem.text...
success {'field_name': 'success'} 1
>>>>>>>>>for elem in tree.findall('.//success'):...if elem.attrib.get('field_name') == "success":...print elem.tag, elem.attrib, elem.text...
success {'field_name': 'success'} 1
Post a Comment for "What Is Python 2.6 Equivalent Of Iterfind()"