0

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!

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.