Search code examples
pythonlxmlcdata

lxml create CDATA element


I am trying to create CDATA element as per https://lxml.de/apidoc/lxml.etree.html#lxml.etree.CDATA

The simplified version of my code looks like this:

description = ET.SubElement(item, "description")
description.text = CDATA('test')

But when I later try to convert it to string:

xml_str = ET.tostring(self.__root, xml_declaration=True).decode()

I get an exception

cannot serialize <lxml.etree.CDATA object at 0x122c30ef0> (type CDATA)

Could you advise me what am I missing?

Here is a simple example:

import xml.etree.cElementTree as ET
from lxml.etree import CDATA


root = ET.Element('rss')
root.set("version", "2.0")
description = ET.SubElement(root, "description")
description.text = CDATA('test')
xml_str = ET.tostring(root, xml_declaration=True).decode()
print(xml_str)

Solution

  • lxml.etree and xml.etree are two different libraries; you should pick one and stick with it, rather than using both and trying to pass objects created by one to the other.

    A working example, using lxml only:

    import lxml.etree as ET
    from lxml.etree import CDATA
    
    root = ET.Element('rss')
    root.set("version", "2.0")
    description = ET.SubElement(root, "description")
    description.text = CDATA('test')
    xml_str = ET.tostring(root, xml_declaration=True).decode()
    print(xml_str)
    

    You can run this yourself at https://replit.com/@CharlesDuffy2/JovialMediumLeadership