Python xml minidom。生成一些文本

2024-10-03 21:31:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码。

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>

这样做容易吗?

奥詹普。。。


Tags: 代码textfromdocheremainversionsome
3条回答

这可以通过toxml()完成,使用正则表达式来整理。

>>> from xml.dom.minidom import Document
>>> import re
>>> 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)
>>> out = doc.toxml()
>>> niceOut = re.sub(r'><', r'>\n<', re.sub(r'(<\/.*?>)', r'\1\n', out))
>>> print niceOut
<?xml version="1.0" ?>
<root>
<Text>Some text here</Text>
</root>

我在找完全一样的东西,我发现了这个帖子。(xml.dom.minidom中提供的缩进破坏了我用来操作xml的另一个工具,我需要缩进它)我用一个稍微复杂一点的示例尝试了接受的解决方案,结果是:

In [1]: import pxdom

In [2]: xml = '<a><b>fda</b><c><b>fdsa</b></c></a>'

In [3]: doc = pxdom.parseString(xml)

In [4]: doc.domConfig.setParameter('format-pretty-print', True)

In [5]: print doc.pxdomContent
<?xml version="1.0" encoding="utf-16"?>
<a>
  <b>fda</b><c>
    <b>fdsa</b>
  </c>
</a>

打印得很漂亮的XML格式不正确,而且我不太喜欢猴子补丁(即我几乎不知道它的意思,也不知道它的坏处),所以我寻找了另一种解决方案。

我正在将输出写入文件,以便可以为Ubuntu使用xmldindent程序($sudo aptitude install xmldindent)。所以我只需将未格式化的写入文件,然后从python程序中调用xmldindent:

from subprocess import Popen, PIPE
Popen(["xmlindent", "-i", "2", "-w", "-f", "-nbe", file_name], 
      stderr=PIPE, 
      stdout=PIPE).communicate()

-w开关会导致文件被覆盖,但令人恼火的是,它会留下一个名为“myfile.xml~”的文件,您可能希望将其删除。其他的开关在那里,以获得正确的格式(为我)。

p.S.xmlindent是流格式化程序,即您可以按如下方式使用它:

cat myfile.xml | xmlindent > myfile_indented.xml

因此,如果需要,您可以在python脚本中使用它,而无需编写文件。

Can this easily be done?

这取决于你想要什么样的规则,但一般来说,你对漂亮的印刷品几乎没有控制权。如果你想要一个特定的格式,你通常必须写自己的沃克。

pxdom中的DOM级别3ls参数格式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进行monkey修补,例如:

>>> 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

所有关于猴子补伤的常见警告都适用。

相关问题 更多 >