码迷,mamicode.com
首页 > 其他好文 > 详细

xml.etree.ElementTree对CDATA的输出

时间:2016-05-30 12:51:57      阅读:956      评论:0      收藏:0      [点我收藏+]

标签:

     xml.etree.ElmentTree不支持CDATA 的输出,但是支持Comment的输出。由于在项目中需要输出带有CDATA块的XML文本,参考Comment的做法,修改ElmentTree中的

_serialize_xml方法中。实现如下:
 

import xml.etree.ElementTree as ET

def CDATA(text=None):
element = ET.Element(‘![CDATA[‘)
element.text = text
return element

ET._original_serialize_xml = ET._serialize_xml

def _serialize_xml(write, elem, qnames, namespaces,short_empty_elements, **kwargs):

if elem.tag == ‘![CDATA[‘:
#write("\n<{}{}]]>\n".format(elem.tag, elem.text))
write("<%s%s]]>" % (elem.tag, elem.text))
if elem.tail:
write(ET._escape_cdata(elem.tail))
else:
return ET._original_serialize_xml(write, elem, qnames, namespaces,short_empty_elements, **kwargs)

ET._serialize_xml = ET._serialize[‘xml‘] = _serialize_xml
 

测试代码:

 

text = """
<?xml version=‘1.0‘ encoding=‘utf-8‘?>
<text>
This is just some sample text.
</text>
"""

e = ET.Element("data")
cdata = MyET.CDATA(text)
e.append(cdata)

#tests
print(ET.tostring(e,encoding="utf-8"))
 
结果:
b"<data><![CDATA[\n<?xml version=‘1.0‘ encoding=‘utf-8‘?>\n<text>\nThis is just some sample text.\n</text>\n]]></data>"
 

xml.etree.ElementTree对CDATA的输出

标签:

原文地址:http://www.cnblogs.com/liaofeifight/p/5541790.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!