标签:
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