Вы можете сначала переименовать тег <plus></plus>
, используя такую библиотеку, как ElementTree
, а затем преобразовать в dict.Вот код:
import xml.etree.ElementTree as ET
import xmltodict
import json
myxml = """
<mydocument has="an attribute">
<and>
<many>elements</many>
<many>more elements</many>
</and>
<plus a="complex">
element as well
</plus>
</mydocument>
"""
#rename tag
root = ET.fromstring(myxml)
for elem in root.iter('plus'):
elem.tag = 'children'
newxml = ET.tostring(root, encoding='utf8', method='xml')
xml_dict = dict(xmltodict.parse(newxml)) #convert to Ordered dict and then a normal dict(optional, OrderedDict is returned by default if only using xmltodict)
print(json.dumps(xml_dict, indent=4)) #pretty print to view dict tree(optional)
#Output:
{
"mydocument": {
"@has": "an attribute",
"and": {
"many": [
"elements",
"more elements"
]
},
"children": {
"@a": "complex",
"#text": "element as well"
}
}
}