如何在xml中添加多个标签?

时间:2018-11-23 18:53:13

标签: python xml python-3.x dictionary tuples

首次使用python处理XML文件。 我想知道如何从字典中添加多个子元素,例如,我有一个名为country的子元素,但是我想创建40个带有country标签的元素,与城市相同: 我有一个这样的tupple:

import xml.etree.cElementTree as ET

dict={'Mexico':'CDMX','US':'Washington','France':'Paris','Japan':'Tokio'}

如何创建具有相同引用的多个标签以及如何传递字典中的值?(我可以创建xml文件,但仅使用一个标签。)

我专注于国家/地区,但无法通过以下关键步骤生成它们:

root = ET.Element("world")

country_tag = ET.SubElement(root, "country")
city = ET.SubElement(country_tag, "city")

for key,value in dict.items():
   ET.Element.append(country)
   country.text = str(key)
tree = ET.ElementTree(root)
tree.write("filename.xml", encoding="UTF-8",xml_declaration=True)

我想生成以下内容:

<world>
    <country>Mexico</country>
        <city>CDMX</city>
    <country>US</country>
        <city>Washington</city>
    <country>France</country>
        <city>Paris</Paris>
    <country>Japan</country>
        <city>Tokio</city>
</world>

我正在使用python 3.7 我还需要知道如何将键和值从字典传递到xml标签。请帮助!!!

0 个答案:

没有答案