我有一个不清楚的xml,并使用python lxml模块对其进行处理。我想在进行任何处理之前将所有\n
内容替换为space
,该如何处理所有元素的文本。
编辑我的xml示例:
<root>
<a> dsdfs\n dsf\n sdf\n</a>
<bds>
<d>sdf\n\n\n\n\n\n</d>
<d>sdf\n\n\nsdf\nsdf\n\n</d>
</bds>
....
....
....
....
</root>
当我打印ittertext时,我不会在输出中得到这个:
root = #get root element
for i in root.ittertext():
print i
dsdfs dsf sdf
dsdfs dsf sdf
sdf nsdf sdf
下面的代码将xml解析为字符串,然后替换\n
为space
,然后写入新的xml文件。您可以在这之间进行其他处理,具体取决于您要执行的操作。
from lxml import etree
tree = etree.parse('some.xml')
root = tree.getroot()
# Get the whole XML content as string
xml_in_str = etree.tostring(root)
# Replace all \n with space
new_xml_data = xml_in_str.replace(r'\n', ' ')
# Do the processing with the new_xml_data string which is formatted
# Maybe also write to a new XML file, without the \n
with open('newxml.xml', 'w') as f:
f.write(new_xml_data)
some.xml
看起来像:
<root>
<a> dsdfs\n dsf\n sdf\n</a>
<bds>
<d>sdf\n\n\n\n\n\n</d>
<d>sdf\n\n\nsdf\nsdf\n\n</d>
</bds>
<bds>
<d>sdf\n\n\n\n\n\n</d>
<d>sdf\n\n\nsdf\nsdf\n\n</d>
</bds>
<bds>
<d>sdf\n\n\n\n\n\n</d>
<d>sdf\n\n\nsdf\nsdf\n\n</d>
</bds>
</root>
newxml.xml
看起来像:
<root>
<a> dsdfs dsf sdf </a>
<bds>
<d>sdf </d>
<d>sdf sdf sdf </d>
</bds>
<bds>
<d>sdf </d>
<d>sdf sdf sdf </d>
</bds>
<bds>
<d>sdf </d>
<d>sdf sdf sdf </d>
</bds>
</root>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句