サンプル集  >  Python  >  XMLとJSONの変換
XMLとJSONの変換
2025/07/19

XMLとJSONの変換の例です。

◆環境
OS Windows 10 Home 22H2 64bit OS x64 プロセッサ
Python 3.13.1
VS Code 1.102.0

XMLとJSONの文字列とdictの相互変換をしてみます。

メソッド
XML文字列dictxmltodict.parse()
dictJSON文字列json.dumps()
JSON文字列dictjson.loads()
dictElement
ElementTree
json2xml.Json2xml().to_xml()
dictXML文字列ET.tostring()

xmltojson.py
 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
23: 
24: 
25: 
26: 
27: 
28: 
29: 
30: 
31: 
32: 
33: 
34: 
35: 
36: 
37: 
38: 
39: 
40: 
41: 
42: 
43: 
44: 
45: 
46: 
47: 
48: 
49: 
50: 
51: 
52: 
53: 
54: 
55: 
56: 
57: 
58: 
59: 
60: 
61: 
62: 
63: 
64: 
65: 
66: 
67: 
68: 
69: 
70: 
import xmltodict
import json
from json2xml import json2xml
from json2xml.utils import readfromjson
import xml.etree.ElementTree as ET
import xml.dom.minidom
import io

def dict_to_xml(tag, d):
    elem = ET.Element(tag)
    for key, val in d.items():
        child = ET.Element(str(key))
        if isinstance(val, dict):
            child.extend(dict_to_xml(key, val))
        else:
            child.text = str(val)
        elem.append(child)
    return elem

xml_string = """
<person>
  <name>XML JSON</name>
  <phone>012-345-6789</phone>
  <email>xml@json.com</email>
</person>
"""


dict_data = xmltodict.parse(xml_string)

print("(1) json.dumps")
json_string = json.dumps(dict_data, indent=4, ensure_ascii=False)
print(type(json_string))
print(json_string)

print("(2) json.loads")
json_data = json.loads(json_string)
print(type(json_data))
print(json_data)

print("(3) json2xml.json2xml(json_string)")
xml_data = json2xml.Json2xml(json_string).to_xml()
print(type(xml_data))
print(xml_data)

print("(4) json2xml.json2xml(json_data)")
xml_data = json2xml.Json2xml(json_data).to_xml()
print(type(xml_data))
print(xml_data)

print("(5) dict_to_xml")
root = dict_to_xml("root", json_data)
print(type(root))
tree = ET.ElementTree(root)
print(type(tree))

print("(5)-1 tree.write")
tree.write("output.xml", encoding="utf-8", xml_declaration=True)
dom = xml.dom.minidom.parse("output.xml")
print(dom.toprettyxml(indent="  "))

print("(5)-2 tree.write(io)")
buffer = io.StringIO()
tree.write(buffer, encoding='unicode', xml_declaration=True)
dom = xml.dom.minidom.parseString(buffer.getvalue())
print(dom.toprettyxml(indent="  "))

print("(5)-3 tree.tostring")
xml_string = ET.tostring(tree.getroot(), encoding="unicode")
print(type(xml_string))
print(xml_string)

実行してみます。

>py xmltojson.py
(1) json.dumps
<class 'str'>
{
    "person": {
        "name": "XML JSON",
        "phone": "012-345-6789",
        "email": "xml@json.com"
    }
}
(2) json.loads
<class 'dict'>
{'person': {'name': 'XML JSON', 'phone': '012-345-6789', 'email': 'xm
l@json.com'}}
(3) json2xml.json2xml(json_string)
<class 'str'>
<?xml version="1.0" encoding="UTF-8"?>
<all>
        <item type="str">{
    "person": {
        "name": "XML JSON",
        "phone": "012-345-6789",
        "email": "xml@json.com"
    }
}</item>
</all>

(4) json2xml.json2xml(json_data)
<class 'str'>
<?xml version="1.0" encoding="UTF-8"?>
<all>
        <person type="dict">
                <name type="str">XML JSON</name>
                <phone type="str">012-345-6789</phone>
                <email type="str">xml@json.com</email>
        </person>
</all>

(5) dict_to_xml
<class 'xml.etree.ElementTree.Element'>
<class 'xml.etree.ElementTree.ElementTree'>
(5)-1 tree.write
<?xml version="1.0" ?>
<root>
  <person>
    <name>XML JSON</name>
    <phone>012-345-6789</phone>
    <email>xml@json.com</email>
  </person>
</root>

(5)-2 tree.write(io)
<?xml version="1.0" ?>
<root>
  <person>
    <name>XML JSON</name>
    <phone>012-345-6789</phone>
    <email>xml@json.com</email>
  </person>
</root>

(5)-3 tree.tostring
<class 'str'>
<root><person><name>XML JSON</name><phone>012-345-6789</phone><email>
xml@json.com</email></person></root>

>

期待通りに動作しました。

▲ PageTop  ■ Home


Copyright (C) 2025 ymlib.com