Python xml minidom.生成<text>一些文本</ text>元素

Orj*_*anp 9 python xml minidom

我有以下代码.

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')
Run Code Online (Sandbox Code Playgroud)

结果是:

<?xml version="1.0" ?>
<root>
    <Text>
        Some text here
    </Text>
</root>
Run Code Online (Sandbox Code Playgroud)

这一切都很好,但是如果我希望输出看起来像这样呢?

<?xml version="1.0" ?>
<root>
    <Text>Some text here</Text>
</root>
Run Code Online (Sandbox Code Playgroud)

这可以轻松完成吗?

Orjanp ...

bob*_*nce 7

这可以轻松完成吗?

这取决于你想要的确切规则,但通常不会,你几乎无法控制漂亮的打印.如果你想要一种特定的格式,你通常需要编写自己的助行器.

pxdom中的DOM Level 3 LS参数格式 - 漂亮打印非常接近您的示例.它的规则是,如果一个元素只包含一个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>
Run Code Online (Sandbox Code Playgroud)

(调整您正在进行的任何类型的序列化的编码和输出格式.)

如果这是你想要的规则,并且你可以逃脱它,你也可能能够修补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
Run Code Online (Sandbox Code Playgroud)

所有关于猴子修补的不良的常见警告都适用.