I have the following XML example
<?xml version="1.0"?>
<test>
<items>
<item>item 1</item>
<item>item 2</item>
</items>
</test>
I need to iterate over each tag in a for loop in python. If tried many things but I just can't get it..
thanks for the help
I personally use xml.etree.cElementTree
, as I've found it works really well, it's fast, easy to use, and works well with big (>2GB) files.
import xml.etree.cElementTree as etree
with open(xml_file_path) as xml_file:
tree = etree.iterparse(xml_file)
for items in tree:
for item in items:
print item.text
In the interactive console
>>> x="""<?xml version="1.0"?>
<test>
<items>
<item>item 1</item>
<item>item 2</item>
</items>
</test>"""
>>> x
'<?xml version="1.0"?>\n<test>\n <items>\n <item>item 1</item>\n <item>item 2</item>\n </items>\n</test>'
>>> import xml.etree.cElementTree as etree
>>> tree = etree.fromstring(x)
>>> tree
<Element 'test' at 0xb63ad248>
>>> for i in tree:
for j in i:
print j
<Element 'item' at 0xb63ad2f0>
<Element 'item' at 0xb63ad338>
>>> for i in tree:
for j in i:
j.text
'item 1'
'item 2'
>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With