# Parsing XML documents with LXML

I'm new to LXML, and parsing XML documents in general. I have written a small section of code that appears to do what I need it too do, but it feels like I have overly complicated it. Is there any way I can simplify this?

Method:

def importFromXML(self, filename):
tree = etree.parse(filename)
for child in tree.getroot():
if child.tag != 'SLOT':
print('Tag:', child.tag, ', Text', child.text)
elif child.tag == 'SLOT':
for slot, index in child.items():
for attribute in child:
print('Slot Number =', index, ', Tag:', attribute.tag, ', Value:', attribute.text)


XML:

<?xml version="1.0" encoding="UTF-8"?>
<Item>
<ActiveState>drop</ActiveState>
<Location>Left Wrist</Location>
<Realm>All</Realm>
<ItemName>Band of the Dream Conqueror</ItemName>
<ItemQuality>100</ItemQuality>
<Equipped>1</Equipped>
<Level>50</Level>
<TYPE>Wrist</TYPE>
<SOURCE>Drop</SOURCE>
<DBSOURCE>kscraft</DBSOURCE>
<SLOT Number="0">
<Type>Resist</Type>
<Effect>Crush</Effect>
<Amount>6</Amount>
</SLOT>
<SLOT Number="1">
<Type>Resist</Type>
<Effect>Thrust</Effect>
<Amount>6</Amount>
</SLOT>
<SLOT Number="2">
<Type>Resist</Type>
<Effect>Slash</Effect>
<Amount>6</Amount>
</SLOT>
</Item>


I just want to make sure I'm doing this right. I'm using Python 3.x. Eventually I will be doing more with the data I pull, but for right now I'm just trying to pull the information, and figure out the most optimized way of doing this.

The code isn't actually doing much, there's little to review to be honest, it's not looking complicated for what it is. Of course don't just have everything in a couple of loops, perhaps have some handlers to dispatch on the tags or so (handlers[child.tag](child) ...).
Finally, there might be a library to automatically map the XML to a class structure, or even parse it directly into dict instances or something, if you prefer that, but I don't any off the top of my hat.
• Thank you. I'm just trying to find the most optimized way to pull the information, then I will do something with it later. There is a lot of terminology that I will need to look up (new to both Python and XML parsing) and see how I can apply it. The XML files are at most 25 lines, and it would be ideal if I could load the <SLOT> elements in a dict that gives me { SLOT: {'Index': value, 'Type': value, 'Effect': value, 'Amount': value}} perhaps that will be my next step. – artomason Feb 4 '18 at 1:36