生成具有适当缩进的 XML 文件

Generating XML file with proper indentation

我正在尝试在 python 中生成 XML 文件,但它没有缩进,输出是直线。

from xml.etree.ElementTree import Element, SubElement, Comment, tostring

name = str(request.POST.get('name'))
top = Element('scenario')
environment = SubElement(top, 'environment')        
cluster = SubElement(top, 'cluster')
cluster.text=name

我尝试使用漂亮的解析器,但它给我一个错误:'Element' object has no attribute 'read'

import xml.dom.minidom

xml_p = xml.dom.minidom.parse(top)
pretty_xml = xml_p.toprettyxml()

提供给解析器的输入格式是否正确?如果这是错误的方法,请建议另一种缩进方法。

你不能直接解析 top 这是一个 Element(),你需要把它变成一个字符串(这就是为什么你应该导入你目前没有使用的 tostring.) ,并在结果上使用 xml.dom.minidom.parseString()

import xml.dom.minidom

xml_p = xml.dom.minidom.parseString(tostring(top))
pretty_xml = xml_p.toprettyxml()
print(pretty_xml)

给出:

<?xml version="1.0" ?>
<scenario>
    <environment/>
    <cluster>xyz</cluster>
</scenario>