LoginSignup
3
3

More than 3 years have passed since last update.

PythonでXMLを辞書にしたり辞書をXMLにしたりする

Last updated at Posted at 2021-02-17

以下ライブラリを使います。

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>要素でラップされたり、属性はうまく復元できないので完全にもとに戻すのは難しそう。

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3