使用 python 编写 XML 文档?
Coding an XML document with 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.
我到处寻找这方面的信息,并得出以下结论。
但是,提交此代码后,我得到以下信息:
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 个具有名称属性的国家/地区节点,第三个是巴拿马。
有人能帮忙吗?
错误消息表明您需要为每个 country
节点包含一个名为 name
的属性。试试这个:
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>
我目前正在参加网络挑战赛,但是我被要求制作一个包含节点和属性的 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 个具有名称属性的国家/地区节点,第三个是巴拿马。
有人能帮忙吗?
错误消息表明您需要为每个 country
节点包含一个名为 name
的属性。试试这个:
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>