Geoff
Geoff

Reputation: 1

Retrieve multiple xml items in a loop with elementtree

I'm trying to loop over an xml file with elementtree. The file looks a bit like this:

<items>
  <item>
    <name>Blah</name>
    <price>1234</price>
  </item>
  <item>
    <name>Something</name>
    <price>2345</price>
  </item>
</items>

After reading this with elementtree, I can do this:

for element in doc.findall('/items/item/name):
  print element.text

But with one loop, I'd like to get the price too... Something like this...

for element in doc.findall('/items/item'):
  print element.name.text
  print element.price.text

...but I can't. Not sure what's next - do I need to do another "find" per "element"?

Many thanks for any help!

Upvotes: 0

Views: 9231

Answers (2)

Piotr Duda
Piotr Duda

Reputation: 1815

Please read the documentation(http://docs.python.org/library/xml.etree.elementtree.html). Here is a working example:

for elem in doc.findall('item'):
   for i in  elem.getchildren():
      print i.text

outputs:

Blah 1234 Something 2345

In my code I iterate over all the items in the xml and retrieve the text assigned with its child nodes.

Upvotes: 4

thomas
thomas

Reputation: 947

You can use the following for granular control over returned values.

for element in doc.findall('item'): # Get the items out.
    # Iterate thought the list of items(They are in element objects)

    print 'Item' # Yey print stuff out!
    print 'Name: ', element.find('name').text
    print 'Price:', element.find('price').text

That outputs the following:

Item
Name: Blah
Price: 1234
Item
Name: Something
Price: 2345

Code first grabs all of the item elements. It then performs a find to get the price and name and prints result. This code ensures that you will always have name printed first and price printed second.

Upvotes: 2

Related Questions