我有以下代码。
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>
这很容易做到吗?
Orjanp...
最佳答案
Can this easily be done?
这取决于您想要的确切规则,但通常不会,您几乎无法控制 pretty-print 。如果您想要特定的格式,您通常必须编写自己的 walker。
pxdom 中的 DOM Level 3 LS 参数 format-pretty-print|非常接近你的例子。它的规则是,如果一个元素只包含一个 TextNode,则不会添加额外的空格。然而,它(目前)使用两个空格而不是四个缩进。
>>> doc= pxdom.parseString('<a><b>c</b></a>')
>>> doc.domConfig.setParameter('format-pretty-print', True)
>>> print doc.pxdomContent
<?xml version="1.0" encoding="utf-16"?>
<a>
<b>c</b>
</a>
(为您正在进行的任何类型的序列化调整编码和输出格式。)
如果这是你想要的规则,并且你可以摆脱它,你也可以猴子修补 minidom 的 Element.writexml,例如:
>>> from xml.dom import minidom
>>> def newwritexml(self, writer, indent= '', addindent= '', newl= ''):
... if len(self.childNodes)==1 and self.firstChild.nodeType==3:
... writer.write(indent)
... self.oldwritexml(writer) # cancel extra whitespace
... writer.write(newl)
... else:
... self.oldwritexml(writer, indent, addindent, newl)
...
>>> minidom.Element.oldwritexml= minidom.Element.writexml
>>> minidom.Element.writexml= newwritexml
所有关于猴子补丁的坏处的常见警告都适用。
关于Python xml 迷你。生成 <text>Some text</text> 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/507405/