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

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

我怎样才能改变我的 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>

我只是想知道是什么导致了这种情况发生?顺便说一句,下面的方法/函数用于添加缩进!

 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>

关于python - 为什么 python 中的元素树在 XML 中添加额外的新行和空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32890494/

相关文章:

python - 使用日期格式设置 X 轴格式

android - 为什么android创建R.java文件

android - 如果我在布局 xml 文件中用自定义 View 类标记替换 "include"标记, View 不会显示,为什么?

python - 检查字符串是否只包含 ASCII 字符?

python - 使用 python 模块 impyla 连接到 Kerberized hadoop 集群

Python 3.4 在 Apache2 服务器 (Mac) 上导致 UnicodeEncodeError 但在命令行中工作正常

python - 使用 python 将图像添加到 powerpoint 文件

python - 可怕的初始值 - 可变类型共享相同的引用?

Python:尝试通过在名片上移动外部边框来获取用户输入

java - IntelliJ IDEA,urn :java? 的 xml namespace