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

时间:2015-10-01 14:46:10

标签: python xml python-2.7 python-3.x elementtree

如何从例如

更改xml的外观
= IF(A5 =< 8, B5 * .07, IF(A5 > 8 AND A5 =< 15, B5 * .05, IF(A5 > 15 AND A5 < 20, B5 * .03, 00.00)))

看起来像:

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

2 个答案:

答案 0 :(得分:5)

一个元素将其包含的文本保存在常规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>

结果:

++

答案 1 :(得分:2)

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

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

 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

相关问题