为什么 python 中的元素树在 XML 中添加了额外的新行和空格

why Element tree in python adds extra new lines and spaces in XML

如何更改 xml 的外观,例如

 <root>
     <elem1>
         <value>
            122
         </value>
         <text>
            This_is_just_a_text
         </text>
     </elem1>
     <elem1>
         <value>
            122
         </value>
         <text>
            This_is_just_a_text
         </text>
     </elem1>   
 </root>

看起来像:

 <root>
     <elem1>
         <value>122</value>
         <text>This_is_just_a_text</text>
     </elem1>
     <elem1>
         <value>122</value>
         <text>This_is_just_a_text</text>
     </elem1>   
 </root>

我只是想知道是什么原因造成的?顺便说一句,下面的 method/function 用于添加缩进!

 def prettify(elem):
     """
         Return a pretty-printed XML string for the Element.
     """
     rough_string = ET.tostring(elem, 'utf-8')
     reparsed = minidom.parseString(rough_string)
     return reparsed.toprettyxml(indent="\t")

元素将其包含的文本保存在常规 str 中,因此您可以调用 str.strip() 来删除不需要的空白。

import xml.etree.ElementTree as ET
import xml.dom.minidom as minidom

def prettify(elem):
     """
         Return a pretty-printed XML string for the Element.
     """
     rough_string = ET.tostring(elem, 'utf-8')
     reparsed = minidom.parseString(rough_string)
     return reparsed.toprettyxml(indent="\t")

def strip(elem):
    for elem in elem.iter():
        if(elem.text):
            elem.text = elem.text.strip()
        if(elem.tail):
            elem.tail = elem.tail.strip()

xml = ET.XML('''<elem1>
         <value>
            122
         </value>
         <text>
            This_is_just_a_text
         </text>
     </elem1>''')

strip(xml)
print prettify(xml)

结果:

<?xml version="1.0" ?>
<elem1>
    <value>122</value>
    <text>This_is_just_a_text</text>
</elem1>

我写这个答案只是为了那些有一天可能会遇到同样问题的人。

这是我发现的!对于 python2.7.3 之前的所有 python 版本,内置方法 toprettyxml() 中实际上存在一个错误,此错误导致在 [=] 中添加冗余空格和新行22=] 输出。因此,如果你有 python 2.7.3 或更高版本,你可以使用问题中提供的 prettify() 方法,你不应该看到任何额外的行或空格,但如果你使用的是旧版本,那么这里是使用 "regular expression":

修复它的方法
 def prettify(elem):
     """
         Return a pretty-printed XML string for the Element.
     """
     rough_string = ET.tostring(elem, 'utf-8')
     reparsed = minidom.parseString(rough_string)
     uglyXml = reparsed.toprettyxml(indent="\t")
     pattern = re.compile('>\n\s+([^<>\s].*?)\n\s+</', re.DOTALL)
     return pattern.sub('>\g<1></', uglyXml) 

Pretty printing XML in Python