我正在尝试在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
我尝试使用漂亮的解析器,但它给我一个错误,因为:“元素”对象没有属性“读取”
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>
关于python - 生成带有适当缩进的XML文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39032046/