15.3. Looping through nodesΒΆ

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:

What do you think this code will print? Run it to see what it actually prints.

The findall method retrieves a Python list of subtrees 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 elements as well as the x attribute from the user node.

Put the following blocks in order to use a loop to process nodes in an XML program, like the one seen above.

It is important to include all parent level elements in the findall statement except for the top level element (e.g., users/user). Otherwise, Python will not find any desired nodes.

What do you think this code will print? Run it to see what it actually prints.

lst stores all user elements that are nested within their users parent. lst2 looks for user elements that are not nested within the top level stuff element where there are none.

You have attempted of activities on this page