【问题标题】:Python toprettyxml() formatting problemsPython toprettyxml() 格式化问题
【发布时间】:2011-06-06 18:23:10
【问题描述】:

我正在尝试使用 Python 的 minidom 处理 XML,然后使用 toprettyxml() 输出结果。我遇到了两个问题:

  1. 添加了空行。
  2. 为文本节点添加了换行符和制表符。

这是代码和输出:

$ 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 这样的外部包。

【问题讨论】:

标签: python xml


【解决方案1】:

一种解决方案是使用 proposed patch 为您提到的错误修补 minidom 库。

我没有测试过自己,也有点hacky,所以它可能不适合你!

【讨论】:

  • 谢谢,我测试了补丁,解决了这两个问题!我没有直接修补 /usr/lib/python 中的 minidom.py,而是做了类似于上面的 ronrothman 链接的操作,其中函数在运行时被替换。这样,它可以在任何地方运行。
  • 嘿,你能分享一下你的补丁解决方案吗?谢谢!
猜你喜欢
  • 2010-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多