簡體   English   中英

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM