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