通過使用xmltodict
到您的XML文件this answer轉換成一個字典,結合扁平化一個dict
,這應該是可能的。
例子:
# Original code: https://codereview.stackexchange.com/a/21035
from collections import OrderedDict
def flatten_dict(d):
def items():
for key, value in d.items():
if isinstance(value, dict):
for subkey, subvalue in flatten_dict(value).items():
yield key + "." + subkey, subvalue
else:
yield key, value
return OrderedDict(items())
import xmltodict
# Convert to dict
with open('test.xml', 'rb') as f:
xml_content = xmltodict.parse(f)
# Flatten dict
flattened_xml = flatten_dict(xml_content)
# Print in desired format
for k,v in flattened_xml.items():
print('{} = {}'.format(k,v))
輸出:
A.B.ConnectionType = a
A.B.StartTime = 00:00:00
A.B.EndTime = 00:00:00
A.B.UseDataDictionary = N
我會看看['xmltodict'](https://github.com/martinblech/xmltodict)庫與[this](http://codereview.stackexchange.com/a/21035) )回答扁平化'dict'。 –