何在Python中使用ElementTree编写具有多个根元素的

何在Python中使用ElementTree编写具有多个根元素的

本文介绍了如何在Python中使用ElementTree编写具有多个根元素的xml文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有python脚本,并且已经使用 xml.etree.cElementTree 编写了写入xml文件的逻辑,该逻辑如下所示

 导入xml.etree.cElementTree作为ET 

root = ET.Element( root)
for I in范围(0,10):
ET.SubElement(root, field1)。text =某个值1
ET.SubElement(root, field2)。text =一些vlaue2

tree = ET.ElementTree(root)
tree.write( filename.xml)

,它给出的输出类似于

 < root> 
< field1>某个值1< / field1>
< field2>某个值2< / field2>
< field1>某个值1< / field1>
< field2>某个值2< / field2>
< field1>某个值1< / field1>
< field2>某个值2< / field2>
< field1>某个值1< / field1>
< field2>一些值2< / field2> ......
< / root>

但我想添加多个根并需要像下面这样放置

 < root> 
< field1>某个值1< / field1>
< field2>某个值2< / field2>
< / root>
< root>
< field1>某个值1< / field1>
< field2>某个值2< / field2>
< / root>
< root>
< field1>某个值1< / field1>
< field2>一些值2< / field2>
< / root>
< root>
< field1>某个值1< / field1>
< field2>一些值2< / field2>
< / root>

是否可以使用 xml.etree.cElementTree 在python中

解决方案

您要生成的无效XML。
参见

还可以始终手动连接字符串。

 将xml.etree.cElementTree导入为ET 
result =''
for I in range(0,10):
root = ET.Element( root)
ET.SubElement(root, field1)。text =某些value1
ET.SubElement(root, field2)。text =一些vlaue2
结果+ = ET.tostring(root)
print(result)#或将结果写入文件


I have python script and I have already written logic of writing xml file using xml.etree.cElementTree and the logic is look like below

import xml.etree.cElementTree as ET

root = ET.Element("root")
for I in range(0,10):
    ET.SubElement(root, "field1").text = "some value1"
    ET.SubElement(root, "field2").text = "some vlaue2"

tree = ET.ElementTree(root)
tree.write("filename.xml")

and it give output like

<root>
      <field1>some value1</field1>
      <field2>some value2</field2>
      <field1>some value1</field1>
      <field2>some value2</field2>
      <field1>some value1</field1>
      <field2>some value2</field2>
      <field1>some value1</field1>
      <field2>some value2</field2>......
</root>

but I want to add multiple root and need out put like below

<root>
  <field1>some value1</field1>
  <field2>some value2</field2>
</root>
<root>
  <field1>some value1</field1>
  <field2>some value2</field2>
</root>
<root>
  <field1>some value1</field1>
  <field2>some value2</field2>
</root>
<root>
  <field1>some value1</field1>
  <field2>some value2</field2>
</root>

is it possible to write like above file using xml.etree.cElementTree in python

解决方案

What you want to generate is not valid xml.See Do you always have to have a root node with xml/xsd? for more info.

Also you can always manually concatenate the string.

import xml.etree.cElementTree as ET
result= ''
for I in range(0, 10):
    root = ET.Element("root")
    ET.SubElement(root, "field1").text = "some value1"
    ET.SubElement(root, "field2").text = "some vlaue2"
    result += ET.tostring(root)
print(result) # or write the result to a file

这篇关于如何在Python中使用ElementTree编写具有多个根元素的xml文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 12:14