【发布时间】:2011-06-06 18:23:10
【问题描述】:
我正在尝试使用 Python 的 minidom 处理 XML,然后使用 toprettyxml() 输出结果。我遇到了两个问题:
- 添加了空行。
- 为文本节点添加了换行符和制表符。
这是代码和输出:
$ cat test.py
from xml.dom import minidom
dom = minidom.parse("test.xml")
print dom.toprettyxml()
$ cat test.xml
<?xml version="1.0" encoding="UTF-8"?>
<store>
<product>
<fruit>orange</fruit>
</product>
</store>
$ python test.py
<?xml version="1.0" ?>
<store>
<product>
<fruit>
orange
</fruit>
</product>
</store>
我可以使用 strip() 删除空白行来解决问题 1,我可以使用此链接中描述的 hack (fixed_writexml) 解决问题 2:http://ronrothman.com/public/leftbraned/xml-dom-minidom-toprettyxml-and-silly-whitespace/,但我想知道自 hack 以来是否有更好的解决方案现在快3岁了。我愿意使用 minidom 以外的东西,但我想避免添加像 lxml 这样的外部包。
【问题讨论】:
-
您可以查看我的解决方案 - stackoverflow.com/a/39984422/2687547
-
这能回答你的问题吗? Empty lines while using minidom.toprettyxml