gpt4 book ai didi

python - 如何使用 python 生成带有节点列表的 xml

转载 作者:行者123 更新时间:2023-12-01 08:05:00 25 4
gpt4 key购买 nike

我遇到了一个问题,其中包括使用 python 生成 xml 文件,但方式略有不同。我认为我误解了这个问题,如果是这样,简单的解释将会有很大帮助。问题是这样的:

Generate a valid xml file at /tmp/vulnerable-countries.xml. It should contain a list of country nodes attached to a root node that have name attributes, the third node should be Panama.

我已经多次尝试这个问题,但我一直收到消息:

Format of /tmp/vulnerable-countries.xml was not correct. It should contain 3 country nodes with name attributes, with the third being Panama.

这是迄今为止我的代码:

import xml.etree.cElementTree as ET

root = ET.Element("root")

ET.SubElement(root, "field1").set('Name','Blah')
ET.SubElement(root, "field2").set('Name','Complete')
ET.SubElement(root, "Panama").set('Name','Panama')

tree = ET.ElementTree(root)
tree.write("/tmp/vulnerable-countries.xml")

显然我做错了什么,但我无法弄清楚。我如何真正解决给我的问题。

最佳答案

怎么样

import xml.etree.ElementTree as ET

root = ET.Element("root")

countries = ['USA', 'Brazil', 'Panama']
for country in countries:
ET.SubElement(root, 'country').set('name', country)

tree = ET.ElementTree(root)
tree.write('c:\\temp\\vulnerable-countries.xml')

输出

<root>
<country name="USA" />
<country name="Brazil" />
<country name="Panama" />
</root>

关于python - 如何使用 python 生成带有节点列表的 xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55579925/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com