I'm parsing an XML file that is structured like this:
<root>
<entry>
<elem1> key </elem1>
<elem2> value </elem2>
</entry>
<entry>
....
</entry>
</root>
</root>
My first code was using .parse()
and .getRoot()
but I had memory issues (1.5G memory use for 350M file). I solved my problem using an iterator and .clear()
after reading this paper.
import xml.etree.ElementTree
myDict = {}
xmlIterator = xml.etree.ElementTree.iterparse('file.xml')
while True:
try:
_ , elem1 = next(xmlIterator)
_ , elem2 = next(xmlIterator)
_ , _ = next(xmlIterator)
except StopIteration:
break
myDict[elem1.text]=elem2
elem1.clear()
elem2.clear()
_.clear()
The issue is I need to access several children at the same time:
- The first one is my key
<elem1>
- The second one is the value I need
<elem2>
- The third is not relevant
<entry>
I would like to know if this is a good practice, or if there is a better way to do that (better performance or readability).
I also tried to follow the "Easier to ask for forgiveness than permission" principle with the exception block for ending the loop, but I'm not sure about multiple statements in the same exception block.
In fact, I also don't understand why the third element I get with next() is <entry>
.