I usually parse XML using the ElemntTree module on the standard library.
Itr does not give you a dictionary, you get a much more useful DOM structure which allows you to iterate over each element for children.
from xml.etree import ElementTree as ET
xml = ET.parse("<path-to-xml-file")
root_element = xml.get_root()
for child in root_element:
...
If there is specific need to parse it to a dicionary, insetead of getting tehinformation you need from a DOM tree, a recursive function to build one from the root node would be soemething like:
def xml_dict(node, path="", dic =None):
if dic == None:
dic = {}
name_prefix = path + ("." if path else "") + node.tag
numbers = set()
for similar_name in dic.keys():
if similar_name.startswith(name_prefix):
numbers.add(int (similar_name[len(name_prefix):].split(".")[0] ) )
if not numbers:
numbers.add(0)
index = max(numbers) + 1
name = name_prefix + str(index)
dic[name] = node.text + "<...>".join(childnode.tail
if childnode.tail is not None else
"" for childnode in node)
for childnode in node:
xml_dict(childnode, name, dic)
return dic
For the XML you list above this yileds this dictionary:
{'A1': '\n \n <...>\n',
'A1.B1': '\n \n <...>\n ',
'A1.B1.C1': '"blah"',
'A1.B1.C2': '"blah"',
'A1.B2': '\n \n <...>\n ',
'A1.B2.C1': '"blah"',
'A1.B2.C2': '"blah"'}
(I find the DOM form more usefull)