【问题标题】:Generating XML file with proper indentation生成具有适当缩进的 XML 文件
【发布时间】:2016-08-19 06:00:19
【问题描述】:

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

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

【问题讨论】:

    标签: python xml xml-parsing xml.etree


    【解决方案1】:

    你不能直接解析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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-13
      • 1970-01-01
      • 2019-07-19
      • 1970-01-01
      • 2010-11-25
      相关资源
      最近更新 更多