The*_*rry 49 python xml elementtree
我试图xml.etree.elementtree用Python写出xml文件.问题在于它们不断生成一行.我希望能够轻松地引用它们,所以如果它可能我真的希望能够干净利落地写出来.
这就是我得到的
<Language><En><Port>Port</Port><UserName>UserName</UserName></En><Ch><Port>IP??</Port><UserName>????</UserName></Ch></Language>
Run Code Online (Sandbox Code Playgroud)
这是我想看到的.
<Language>
<En>
<Port>Port</Port>
<UserName>UserName</UserName>
</En>
<Ch>
<Port>IP??</Port>
<UserName>????</UserName>
</Ch>
</Language>
Run Code Online (Sandbox Code Playgroud)
Max*_*amy 59
您可以使用该功能toprettyxml()从xml.dom.minidom为了做到这一点:
def prettify(elem):
"""Return a pretty-printed XML string for the Element.
"""
rough_string = ElementTree.tostring(elem, 'utf-8')
reparsed = minidom.parseString(rough_string)
return reparsed.toprettyxml(indent="\t")
Run Code Online (Sandbox Code Playgroud)
我们的想法是Element在字符串中打印,使用minidom解析它并使用该toprettyxml函数再次在XML中进行转换.
资料来源:http://pymotw.com/2/xml/etree/ElementTree/create.html
use*_*019 21
您可以使用库lxml,它是ElementTree的超集.它的tostring()方法包含一个参数pretty_print - 例如:
>>> print(etree.tostring(root, pretty_print=True))
<root>
<child1/>
<child2/>
<child3/>
</root>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
91851 次 |
| 最近记录: |