[英]How can i add a full new Element (using ElementTree in Python) to a XML File
i have the code posted below, i could add a new Element "continent" to country "Singapore".我在下面发布了代码,我可以向国家“新加坡”添加一个新元素“大陆”。 But i want to add a full Element to the XML File.
但我想在 XML 文件中添加一个完整的元素。 Is it possible to do that?
有可能这样做吗? The "data" variable contains the content of the Element i want to create in the XML File.
“数据”变量包含我想在 XML 文件中创建的元素的内容。 I tried to append it but... no luck!
我尝试了 append 但......没有运气!
My XML File:我的 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>
Here is my Python code:这是我的 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")
try this:尝试这个:
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")
important is this part, where you generate an xml object hierarchy for your xml snippet (data) and attach it as child to your root node:这部分很重要,您在其中为您的 xml 片段(数据)生成 xml object 层次结构并将其作为子节点附加到根节点:
new2 = et.fromstring(data)
root.append(new2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.