Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python XML to dictionary to iterate over items

Tags:

python

xml

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

like image 272
Mike Avatar asked Feb 27 '23 11:02

Mike


1 Answers

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'
>>>
like image 122
Esteban Küber Avatar answered Mar 09 '23 17:03

Esteban Küber