Xml.etree.ElementTree output to CDATA

Source: Internet
Author: User
Tags cdata



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


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.