以下ライブラリを使います。
PyPI:https://pypi.org/project/xmltodict/
GitHub:https://github.com/martinblech/xmltodict
PyPI:https://pypi.org/project/dicttoxml/
GitHub:https://github.com/quandyfactory/dicttoxml
インストール方法
>pip install xmltodict
>pip install dicttoxml
実装
convert_xml.py
import xmltodict
import dicttoxml
import json
xml = """<?xml version="1.0" encoding="UTF-8" ?>
<foods>
<food>
<name>イチゴ</name>
<color>赤</color>
</food>
<food>
<name>バナナ</name>
<color>黄</color>
</food>
</foods>
"""
# XMLから辞書に変換
dict_xml = xmltodict.parse(xml)
print(json.dumps(dict_xml, indent=2, ensure_ascii=False))
# 辞書からXMLに変換
# attr_type:属性に型名を付ける
# root:rootの要素を付与する
xml = dicttoxml.dicttoxml(dict_xml, attr_type=False, root=False)
print(xml.decode('utf-8'))
結果
>python convert_xml.py
{
"foods": {
"food": [
{
"name": "イチゴ",
"color": "赤"
},
{
"name": "バナナ",
"color": "黄"
}
]
}
}
<foods><food><item><name>イチゴ</name><color>赤</color></item><item><name>バナナ</name><color>黄</color></item></food></foods>
配列は<item>
要素でラップされたり、属性はうまく復元できないので完全にもとに戻すのは難しそう。