Reputation: 31
I want to parse an XML content and return a dictionary which contains only the name attribute and its values as dictionary. For example:
<ecmaarray>
<number name="xyz1">123.456</number>
<ecmaarray name="xyz2">
<string name="str1">aaa</string>
<number name="num1">55</number>
</ecmaarray>
<strictarray name="xyz3">
<string>aaa</string>
<number>55</number>
</strictarray>
</ecmaarray>
The output has to be in a dictionary something like this..
Dict:{ 'xyz1': 123.456,
'xyz2': {'str1':'aaa', 'num1': '55'},
'xyz3': ['aaa','55']
}
Can any one suggest a recursive solution for this ?
Upvotes: 2
Views: 550
Reputation: 473853
Assuming situation like this:
<strictarray name="xyz4">
<string>aaa</string>
<number name="num1">55</number>
</strictarray>
is not possible, here's a sample code using lxml
:
from lxml import etree
tree = etree.parse('test.xml')
result = {}
for element in tree.xpath('/ecmaarray/*'):
name = element.attrib["name"]
text = element.text
childs = element.getchildren()
if not childs:
result[name] = text
else:
child_dict = {}
child_list = []
for child in childs:
child_name = child.attrib.get('name')
child_text = child.text
if child_name:
child_dict[child_name] = child_text
else:
child_list.append(child_text)
if child_dict:
result[name] = child_dict
else:
result[name] = child_list
print result
prints:
{'xyz3': ['aaa', '55'],
'xyz2': {'str1': 'aaa', 'num1': '55'},
'xyz1': '123.456'}
You may want to improve the code - it's just a hint on where to go.
Hope that helps.
Upvotes: 1