次のサンプルを試してください。以下の出力を参照してください。のコンテンツとして使用されたものを示しますmy.xml
。要素は、子のリストとして動作します (つまり、反復することもできます)。必要なすべての要素をドキュメント順序で取得するための関数とイテレータがあります (つまり、それらの深さ、子などは関係ありません)。は属性のelement.attrib
ディクショナリとして動作します。標準xml.etree.ElementTree
は XPath のサブセットもサポートします -- 末尾を参照してください:
import xml.etree.ElementTree as et
tree = et.parse('my.xml')
root = tree.getroot() # the root element of the tree
et.dump(root) # here is how the input file looks inside
# Any element behaves as a list of children. This way, the last child
# of the list can be accessed via negative index.
print '-------------------------------------------'
print root[-1]
# Here is the content.
print '-------------------------------------------'
et.dump(root[-1])
# If the elements could be not direct children, you can use findall('tag') to
# get the list of the elements. Then you access it again as the last element
# of the list
print '-------------------------------------------'
lst = root.findall('testCase')
et.dump(lst[-1])
# The number of the 'testCase' elements is simply the length of the list.
print '-------------------------------------------'
print 'Num. of test cases:', len(lst)
# The elem.iter('tag') works similarly. But if you want the last element,
# you must know when the element is the last one. It means you have to
# loop through all of them anyway.
print '-------------------------------------------'
last = None # init
for e in root.iter('testCase'):
last = e
et.dump(last)
# The attributes of the elements take the form of the dictinary .attrib.
print '-------------------------------------------'
print last.attrib
print last.attrib['name']
# The standard xml.etree.ElementTree supports a subset of XPath. You can use
# it if you are familiar with XPath.
print '-------------------------------------------'
third = root.find('.//testCase[3]')
et.dump(third)
# ... including the last() function. For more complex cases, use lxml
# as pointed out by Emmanuel.
print '-------------------------------------------'
last = root.find('.//testCase[last()]')
et.dump(last)
コンソールに次のように出力されます。
c:\tmp\___python\Sunny\so12669404>python a.py
<root>
<testCase name="a" />
<testCase name="b" />
<testCase name="c" />
<testCase name="d" />
</root>
-------------------------------------------
<Element 'testCase' at 0x231a630>
-------------------------------------------
<testCase name="d" />
-------------------------------------------
<testCase name="d" />
-------------------------------------------
Num. of test cases: 4
-------------------------------------------
<testCase name="d" />
-------------------------------------------
{'name': 'd'}
d
-------------------------------------------
<testCase name="c" />
-------------------------------------------
<testCase name="d" />