我有python脚本,我已经编写了使用xml.etree.cElementTree
编写xml文件的逻辑,逻辑如下所示
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")
并提供类似
的输出<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>
但是我想添加多个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>
<root>
<field1>some value1</field1>
<field2>some value2</field2>
</root>
是否可以使用python
中的xml.etree.cElementTree
来编写上述文件
答案 0 :(得分:1)
您要生成的内容不是有效的xml。 有关详细信息,请参阅Do you always have to have a root node with xml/xsd?。
此外,您始终可以手动连接字符串。
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