【问题标题】:Appending to a file in ElementTree (Json to XML)附加到 ElementTree 中的文件(Json 到 XML)
【发布时间】:2021-07-06 16:14:38
【问题描述】:

我希望将几个 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")

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

我需要这样的输出

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

【问题讨论】:

  • 您忘记显示所需的输出 XML。
  • 我用预期的输出编辑了它

标签: python json xml elementtree


【解决方案1】:

将文字移出循环。

>>> 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

【讨论】:

  • 谢谢,这似乎有效。有没有办法正确格式化xml文件?
  • 定义“正确格式化 xml 文件”。你的意思是prettify
  • 是的,我的意思是漂亮。生病检查美化
  • 如果你有 python 3.9,你可以在我编辑的答案中使用 ET.indent。
猜你喜欢
  • 2013-05-13
  • 1970-01-01
  • 1970-01-01
  • 2016-01-20
  • 2012-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多