2011-06-06 868 views
2

我想使用Python的minidom处理XML,然后使用toprettyxml()输出结果。我碰到两个问题:Python 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> 

我可以解决办法使用条问题1()以除去空行,我可以使用在此链路中描述的劈(fixed_writexml)解决方法的问题2: http://ronrothman.com/public/leftbraned/xml-dom-minidom-toprettyxml-and-silly-whitespace/,但我想知道是否有更好的解决方案,因为黑客现在已经快3岁了。我打算使用minidom以外的东西,但我想避免添加像lxml这样的外部包。

+0

您可以登出我的解决方案 - http://stackoverflow.com/a/39984422/2687547 – dganesh2002 2016-10-21 22:28:43

回答

2

一个解决方案是将minidom库与proposed patch修补到您提到的错误。

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

+1

谢谢,我测试了这个补丁,它解决了这两个问题!我没有在/ usr/lib/python中直接修改minidom.py,而是做了类似于上面的ronrothman链接,在运行时替换了函数。这样,它可以在任何地方运行。 – Ravi 2011-06-06 19:23:24

+2

嘿,你可以请你把解决方案分享给补丁吗?谢谢 ! – Igal 2013-01-23 14:43:07