Xml.etree.ElmentTree does not support CDATA output, but it supports comment output. Since you need to output XML text with CDATA blocks in your project, refer to the comment approach and modify the Elmenttree in the
The _serialize_xml method. The implementation is as follows:
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
Test code:
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"))
Results:
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 output to CDATA