[英]How can i add a full new Element (using ElementTree in Python) to a XML File
我在下面發布了代碼,我可以向國家“新加坡”添加一個新元素“大陸”。 但我想在 XML 文件中添加一個完整的元素。 有可能這樣做嗎? “數據”變量包含我想在 XML 文件中創建的元素的內容。 我嘗試了 append 但......沒有運氣!
我的 XML 文件:
<data>
<country name="Liechtenstein">
<rank updated="yes">5</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor direction="E" name="Austria" />
<neighbor direction="W" name="Switzerland" />
</country>
<country name="Singapore">
<rank updated="yes">8</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor direction="N" name="Malaysia" />
</country>
<country name="Panama">
<rank updated="yes">72</rank>
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor direction="W" name="Costa Rica" />
<neighbor direction="E" name="Colombia" />
</country>
</data>
這是我的 Python 代碼:
import xml.etree.ElementTree as et
for item in root.findall("country"):
if(item.get("name") == "Singapore"):
new1 = et.Element("continent")
new1.text = "Asia"
item.append(new1)
tree.write("countries.xml")
data = '''
<country name="Portugal">
<rank updated="yes">21</rank>
<year>2000</year>
<gdppc>150000</gdppc>
<neighbor direction="E" name="Spain" />
</country>
'''
new2 = et.Element("country")
new2.text = data
root.append(new2)
tree.write("countries.xml")
嘗試這個:
import xml.etree.ElementTree as et
xml = """
<data>
<country name="Liechtenstein">
<rank updated="yes">5</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor direction="E" name="Austria" />
<neighbor direction="W" name="Switzerland" />
</country>
<country name="Singapore">
<rank updated="yes">8</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor direction="N" name="Malaysia" />
</country>
<country name="Panama">
<rank updated="yes">72</rank>
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor direction="W" name="Costa Rica" />
<neighbor direction="E" name="Colombia" />
</country>
</data>
"""
if __name__ == "__main__":
tree = et.ElementTree(et.fromstring(xml))
root = tree.getroot()
data = '''
<country name="Portugal">
<rank updated="yes">21</rank>
<year>2000</year>
<gdppc>150000</gdppc>
<neighbor direction="E" name="Spain" />
</country>
'''
new2 = et.fromstring(data)
root.append(new2)
tree.write("countries2.xml")
這部分很重要,您在其中為您的 xml 片段(數據)生成 xml object 層次結構並將其作為子節點附加到根節點:
new2 = et.fromstring(data)
root.append(new2)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.