TAGS :Viewed: 22 - Published at: a few seconds ago

[ turning xml file to a dictionary ]

i got the following xml (partly file):

<BikoretNo>8</BikoretNo>
<DllVerNo>8.0.1.0</DllVerNo>
-<Item>
   <ItemCode>11210000094</ItemCode>
   <ItemName>tobasco 60 m"m</ItemName>
   <ManufactureCountry>US</ManufactureCountry>
   <Quantity>60.00</Quantity>
   <ItemPrice>12.80</ItemPrice>
</Item>
-<Item>
   <ItemCode>13495113506</ItemCode>
   <ItemName>klik 75</ItemName>
   <ManufactureCountry>IL</ManufactureCountry>
   <Quantity>75.00</Quantity>
   <ItemPrice>5.00</ItemPrice>
</Item>

i need to turn the following xml file to the following dictionary:

{
  11210000094 :{
               ItemCode:11210000094,
               ItemName:klik 75,ManufactureCountry:IL,
               ...
               },
 13495113506: {
               ItemCode:13495113506,
               ...
              }
 }

Answer 1


For this sample xml data that i save to a file called filename.xml:

<?xml version="1.0" encoding="utf-8"?> 
<body> 
<BikoretNo>8</BikoretNo>
<DllVerNo>8.0.1.0</DllVerNo>
<Item> 
   <ItemCode>11210000094</ItemCode>
   <ItemName>tobasco 60 m"m</ItemName>
   <ManufactureCountry>US</ManufactureCountry>
   <Quantity>60.00</Quantity>
   <ItemPrice>12.80</ItemPrice>
</Item>
<Item> 
   <ItemCode>13495113506</ItemCode>
   <ItemName>klik 75</ItemName>
   <ManufactureCountry>IL</ManufactureCountry>
   <Quantity>75.00</Quantity>
   <ItemPrice>5.00</ItemPrice>
</Item>
</body>

The code looks like:

import xml.etree.ElementTree as ET

root = ET.parse('filename.xml').getroot()
data_set = {}

for node in root:
    if node.tag == 'Item':
        item = {child.tag: child.text for child in node}
        item_code = item['ItemCode']
        data_set[item_code] = item
print data_set

And the output looks like (i've formatted it for readability):

{
    '11210000094': {
        'ItemPrice': '12.80',
        'ItemCode': '11210000094',
        'ItemName': 'tobasco 60 m"m',
        'ManufactureCountry': 'US',
        'Quantity': '60.00'
     },
    '13495113506': {
        'ItemPrice': '5.00', 
        'ItemCode': '13495113506', 
        'ItemName': 'klik 75', 
        'ManufactureCountry': 'IL', 
        'Quantity': '75.00'
    }
}