您在這裡

Looping through nodes

24 二月, 2015 - 11:18

Often the XML has multiple nodes and we need to write a loop to process all of the nodes. In the following program, we loop through all of the user nodes:

import xml.etree.ElementTree as ET

input = '''<stuff>    <users>        <user x="2">            <id>001</id>            <name>Chuck</name>        </user>        <user x="7">            <id>009</id>            <name>Brent</name>        </user>    </users></stuff>'''

stuff = ET.fromstring(input)lst = stuff.findall('users/user')print 'User count:', len(lst)

for item in lst:    print 'Name', item.find('name').text    print 'Id', item.find('id').text    print 'Attribute', item.get('x')

The findall method retrieves a Python list of su b-trees that represent the user structures in the XML tree. Then we can write a for loop that looks at each of the user nodes, and prints the name and id text elem ents as well as the x attribute from the user node.

User count: 2Name ChuckId 001Attribute 2Name BrentId 009Attribute 7