使用python编写XML文档?

时间:2018-03-01 15:28:52

标签: python xml elementtree

我目前正在参加网络挑战赛,但我要求制作一个包含节点和属性的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.

我到处寻找有关这方面的信息,我想到了以下内容。 但是,在提交此代码后,我得到以下内容:

import xml.etree.cElementTree as ET

root = ET.Element("root")
ET.SubElement(root, "Country")
ET.SubElement(root, "Country")
ET.SubElement(root, "Panama")
tree = ET.ElementTree(root)
tree.write("/tmp/vulnerable-countries.xml")

/tmp/vulnerable-countries.xml的格式不正确。它应该包含3个具有名称属性的国家节点,第三个节点是巴拿马。

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

错误消息表明您需要为每个name节点包含一个名为country的属性。试试这个:

import xml.etree.cElementTree as ET

root = ET.Element("root")
ET.SubElement(root, "country", name="Narnia")
ET.SubElement(root, "country", name="Wakanda")
ET.SubElement(root, "country", name="Panama")
tree = ET.ElementTree(root)
tree.write("/tmp/vulnerable-countries.xml")

结果:

<root><country name="Narnia" /><country name="Wakanda" /><country name="Panama" /></root>