Jed*_*ani 2 python xml elementtree python-2.7 python-3.x
我怎样才能改变我的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>
Run Code Online (Sandbox Code Playgroud)
看起来像:
<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>
Run Code Online (Sandbox Code Playgroud)
我只是想知道是什么原因发生的?顺便说一句,下面的方法/函数用于添加缩进!
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")
Run Code Online (Sandbox Code Playgroud)
Element将其包含的文本保存在常规文本中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)
Run Code Online (Sandbox Code Playgroud)
结果:
<?xml version="1.0" ?>
<elem1>
<value>122</value>
<text>This_is_just_a_text</text>
</elem1>
Run Code Online (Sandbox Code Playgroud)