我有以下代码。
from xml.dom.minidom import Document
doc = Document()
root = doc.createElement('root')
doc.appendChild(root)
main = doc.createElement('Text')
root.appendChild(main)
text = doc.createTextNode('Some text here')
main.appendChild(text)
print doc.toprettyxml(indent='\t')
结果是:
<?xml version="1.0" ?>
<root>
<Text>
Some text here
</Text>
</root>
这一切都很好,但如果我希望输出像这样呢?
<?xml version="1.0" ?>
<root>
<Text>Some text here</Text>
</root>
这样做容易吗?
奥詹普。。。
这可以通过toxml()完成,使用正则表达式来整理。
我在找完全一样的东西,我发现了这个帖子。(xml.dom.minidom中提供的缩进破坏了我用来操作xml的另一个工具,我需要缩进它)我用一个稍微复杂一点的示例尝试了接受的解决方案,结果是:
打印得很漂亮的XML格式不正确,而且我不太喜欢猴子补丁(即我几乎不知道它的意思,也不知道它的坏处),所以我寻找了另一种解决方案。
我正在将输出写入文件,以便可以为Ubuntu使用xmldindent程序($sudo aptitude install xmldindent)。所以我只需将未格式化的写入文件,然后从python程序中调用xmldindent:
-w开关会导致文件被覆盖,但令人恼火的是,它会留下一个名为“myfile.xml~”的文件,您可能希望将其删除。其他的开关在那里,以获得正确的格式(为我)。
p.S.xmlindent是流格式化程序,即您可以按如下方式使用它:
因此,如果需要,您可以在python脚本中使用它,而无需编写文件。
这取决于你想要什么样的规则,但一般来说,你对漂亮的印刷品几乎没有控制权。如果你想要一个特定的格式,你通常必须写自己的沃克。
pxdom中的DOM级别3ls参数格式pretty print非常接近您的示例。它的规则是,如果一个元素只包含一个TextNode,则不会添加额外的空白。但是它(当前)使用两个空格来缩进,而不是四个空格。
(调整编码和输出格式以适应正在进行的任何类型的序列化。)
如果这是您想要的规则,并且您可以摆脱它,那么您还可以对minidom的Element.writexml进行monkey修补,例如:
所有关于猴子补伤的常见警告都适用。
相关问题 更多 >
编程相关推荐