簡體   English   中英

Python xml minidom。 生成 <text> 一些文字 </text> 元件

[英]Python xml minidom. generate <text>Some text</text> element

我有以下代碼。

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

這可以輕松完成嗎?

這取決於你想要的確切規則,但通常不是,你幾乎無法控制漂亮的打印。 如果你想要一種特定的格式,你通常需要編寫自己的助行器。

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>

(調整您正在進行的任何類型的序列化的編碼和輸出格式。)

如果這是你想要的規則,並且你可以逃脫它,你也可以修補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

所有關於猴子修補的不良的常見警告都適用。

我正在尋找完全相同的東西,我遇到了這篇文章。 (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格式不正確,我對猴子修補不太滿意(即我幾乎不知道它意味着什么,並且理解它很糟糕),所以我尋找另一個解決方案。

我正在將輸出寫入文件,因此我可以將xmlindent程序用於Ubuntu($ sudo aptitude install xmlindent)。 所以我只是將未格式化的文件寫入文件,然后在python程序中調用xmlindent:

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

-w開關導致文件被覆蓋,但煩人地留下了一個你可能想要刪除的命名例如“myfile.xml~”。 其他開關是為了獲得正確的格式(對我而言)。

PS xmlindent是一個流格式化程序,即您可以按如下方式使用它:

cat myfile.xml | xmlindent > myfile_indented.xml

因此,如果需要,您可以在python腳本中使用它而無需寫入文件。

這可以使用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>

這個解決方案適用於我沒有猴子修補或停止使用minidom:

from xml.dom.ext import PrettyPrint
from StringIO import StringIO

def toprettyxml_fixed (node, encoding='utf-8'):
    tmpStream = StringIO()
    PrettyPrint(node, stream=tmpStream, encoding=encoding)
    return tmpStream.getvalue()

http://ronrothman.com/public/leftbraned/xml-dom-minidom-toprettyxml-and-silly-whitespace/#best-solution

最簡單的方法是使用prettyxml,並刪除標簽內的\\ n和\\ tt。 這樣你就可以按照例子中的要求保留縮進。

xml_output = doc.toprettyxml() nojunkintags = re.sub('>(\\n|\\t)</', '', xml_output) print nojunkintags

pyxml包通過使用xml.dom.ext.PrettyPrint()函數為此提供了一個簡單的解決方案。 它還可以打印到文件描述符。

但不再維護pyxml包。

Oerjan Pettersen

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM