附加到ElementTree中的文件(Json到XML)



我希望将几个Json条目转换为XML。

我的Json文件看起来像这个

{
"list": [
{"id":1,"author":"abc","title":"xyz"},
{"id":2,"author":"def","title":"mno"}
]
}

我现在使用的代码:

import json as j
import xml.etree.cElementTree as e
with open('data.json') as data_file:    
data = j.load(data_file)
for obj in data['list']:
r = e.Element("sequence")
e.SubElement(r,"id").text = obj["id"]
e.SubElement(r,"submitter").text = obj["submitter"]
e.SubElement(r,"authors").text = str(obj["authors"])
e.SubElement(r,"title").text = str(obj["title"])   
a = e.ElementTree(r)
a.write("json_to_xml.xml")

我需要像.append((而不是.write((这样的东西,因为它每次都被覆盖,最后我只得到1个结果。有这样的东西吗?

我需要输出看起来像这个

<sequence>
<id>1</id>
<author>abc</author>
<title>xyz</title>
</sequence>
<sequence>
<id>2</id>
<author>def</author>
<title>mno</title>
</sequence>

将写入移动到循环之外。

>>> from xml.etree import ElementTree as ET
>>> import json
>>> from io import BytesIO
>>>
>>> data = '''
... {
...     "list": [
...          {"id":1,"author":"abc","title":"xyz"},
...          {"id":2,"author":"def","title":"mno"}
...     ]
... }
... '''
>>>
>>> d = json.loads(data)
>>>
>>> r = ET.Element("sequence")
>>> for obj in d['list']:
...     ET.SubElement(r, "id").text = str(obj["id"])
...     ET.SubElement(r, "author").text = str(obj["author"])
...     ET.SubElement(r, "title").text = str(obj["title"])
...
>>>
>>> a = ET.ElementTree(r)
>>> ET.indent(a) # new in 3.9
>>> f = BytesIO()
>>> a.write(f)
>>>
>>> print(f.getvalue().decode('UTF8'))
<sequence>
<id>1</id>
<author>abc</author>
<title>xyz</title>
<id>2</id>
<author>def</author>
<title>mno</title>
</sequence>
>>>

如果你有python 3.9,你可以使用ET.indent.

最新更新