xml.etree.ElementTree對CDATA的輸出

     xml.etree.ElmentTree不支持CDATA 的輸出,可是支持Comment的輸出。因爲在項目中須要輸出帶有CDATA塊的XML文本,參考Comment的作法,修改ElmentTree中的app

_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>"
相關文章
相關標籤/搜索