如何写在Python中

问题描述:

使用ElementTree的我有python脚本,我已经写了使用xml.etree.cElementTree编写XML文件的逻辑和逻辑看起来像下面如何写在Python中

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") 

,并给它输出多根元素的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> 
    <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> 

是否可以使用xml.etree.cElementTree在python中编写上述文件

您要生成的内容不是有效的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