わずかにきれいな辞書を与えるために、ダニエルの答えの私の修正:
def xml_to_dictionary(element):
l = len(namespace)
dictionary={}
tag = element.tag[l:]
if element.text:
if (element.text == ' '):
dictionary[tag] = {}
else:
dictionary[tag] = element.text
children = element.getchildren()
if children:
subdictionary = {}
for child in children:
for k,v in xml_to_dictionary(child).items():
if k in subdictionary:
if ( isinstance(subdictionary[k], list)):
subdictionary[k].append(v)
else:
subdictionary[k] = [subdictionary[k], v]
else:
subdictionary[k] = v
if (dictionary[tag] == {}):
dictionary[tag] = subdictionary
else:
dictionary[tag] = [dictionary[tag], subdictionary]
if element.attrib:
attribs = {}
for k,v in element.attrib.items():
attribs[k] = v
if (dictionary[tag] == {}):
dictionary[tag] = attribs
else:
dictionary[tag] = [dictionary[tag], attribs]
return dictionary
namespace は、ElementTree がすべてのタグの先頭に追加する中かっこを含む xmlns 文字列です。ドキュメント全体に対して 1 つの名前空間があるため、ここではそれをクリアしました。
未加工の xml も調整したことに注意してください。そのため、「空の」タグは、ElementTree 表現で最大で ' ' テキスト プロパティを生成します。
spacepattern = re.compile(r'\s+')
mydictionary = xml_to_dictionary(ElementTree.XML(spacepattern.sub(' ', content)))
たとえば、
{'note': {'to': 'Tove',
'from': 'Jani',
'heading': 'Reminder',
'body': "Don't forget me this weekend!"}}
基本的にjsonと同等の特定のxml用に設計されており、次のような要素属性を処理する必要があります
<elementName attributeName='attributeContent'>elementContent</elementName>
それも
リストをネストするのが適切なようですが、繰り返しサブタグがマージされる方法と同様に、属性辞書/サブタグ辞書をマージする可能性があります:-)