0

I am learning Python right now on version 2.6.4 The first thing I am trying to do is trying to parse only the value of an attribute (orderno) and print those out. Secondly I am trying to parse through the XML and find a value of an attribute like 10238 from attribut "orderno", but print out the whole item as a csv line like "10238,1,Hasselblad 501 CM body,2355" Any pointers on how to do it?

from xml.etree import ElementTree
tree = ElementTree.parse('sample.xml')
root = tree.getroot()

for item in root:
    first = item.find('orderno').text
    print first

Data:

<item> 
<orderno>10238</orderno>
<count>1</count>
<name>Hasselblad 501 CM body</name> 
<price>2355</price>
</item> 
<item> 
<orderno>20032</orderno>
<count>1</count>
<name>Carl Zeiss Planar Lens CB 2.8/80 mm</name>
<price>1233</price>
</item> 
<item>
<orderno>30212</orderno>
<count>1</count>
<name>Roll Film 120 Magazine A12</name>
<price>917</price>
</item> 
4
  • It would be easier if the data had <items> tag Commented Mar 10, 2017 at 13:25
  • that was just an example. I edited the sample.xml. Commented Mar 10, 2017 at 13:33
  • um, if this is python then it's in serious need of code indentation, current one just confuses me Commented Mar 10, 2017 at 13:37
  • Your xml didn't change doesn't affect my comment. Regardless, you have no logic to find every item tag. Please try it Commented Mar 10, 2017 at 13:39

1 Answer 1

1

You basically need to iterate through all subelements. Here I've iterated through the sub items through list comprehension and joined the list with comma!

from xml.etree import ElementTree
tree = ElementTree.parse('sample.xml')
root = tree.getroot()

for item in root:
    print ','.join([sub_item.text for sub_item in item])

Sample Output:

10238,1,Hasselblad 501 CM body,2355
20032,1,Carl Zeiss Planar Lens CB 2.8/80 mm,1233
30212,1,Roll Film 120 Magazine A12,917

Hope it helps!

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

1 Comment

Works perfectly!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.