2

我正在尝试在 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()

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

4

1 回答 1

2

您不能直接解析topwhich is an 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>
于 2016-08-19T06:24:20.523 回答