0

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)
3
  • Cannot reproduce. Please provide a minimal reproducible example. Commented Jul 8, 2022 at 14:57
  • I have added a simple example, Python 3.8.10, lxml 4.8.0. Commented Jul 8, 2022 at 20:21
  • Use lxml.etree or xml.etree; don't mix them. Commented Jul 8, 2022 at 20:23

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.