将XML(ET.Element)写入文件

时间:2014-09-15 11:17:15

标签: python xml python-2.7 xml-parsing

我使用xml.etree.ElementTree创建了一个XML文件。 创建的XML基本上如下所示:

<testsuite name="Exploatering Tests">
   <testsuite name="device"></testsuite>
   <testsuite name="management"></testsuite>
   <testsuite name="auto"></testsuite>
</testsuite>

一切看起来不错,但我想只将子元素导出到文件中,为此我使用以下代码:

# First Testsuite Level
testsuite_exploatering = ET.Element('testsuite')
testsuite_exploatering.set("name", "Exploatering Tests")
... HERE I RECURSIVELY ADD LOTS OF ELEMENT TO testsuite_exploatering
# Write XML to file
output_xml = ET.ElementTree(testsuite_exploatering)
ET.ElementTree.write(testsuite_exploatering, output_file, xml_declaration=True, encoding="UTF-8")

它正确地将XML元素写入文件,但是我应该如何修改它以仅将内部元素打印到文件中(我不希望将Exploatering Tests元素写入文件中)。希望文件看起来像这样:

   <testsuite name="device"></testsuite>
   <testsuite name="management"></testsuite>
   <testsuite name="auto"></testsuite>

1 个答案:

答案 0 :(得分:0)

我不确定这是一个合法的XML结构。如果你真的想强制输出为那种格式,也许你可以迭代孩子们并像这样写下每一个:

    out_handle = open('output.xml','w')
    for child in testsuite_exploatering.getchildren():
            ET.ElementTree.write(ET.ElementTree(child), out_handle)
    out_handle.close()