0
votes

I know that I can preserve CDATA sections during XML parsing, using the following:

from lxml import etree

parser = etree.XMLParser(strip_cdata=False)
root = etree.XML('<root><![CDATA[test]]></root>', parser)

See APIs specific to lxml.etree

But, is there a simple way to "restore" CDATA section during serialization? For example, by specifying a list of tag names…

For instance, I want to turn:

<CONFIG>
    <BODY>This is a &lt;message&gt;.</BODY>
</CONFIG>

to:

<CONFIG>
    <BODY><![CDATA[This is a <message>.]]></BODY>
</CONFIG>

Just by telling that BODY should contains CDATA…

1

1 Answers

1
votes

Something like this?

from lxml import etree

parser = etree.XMLParser(strip_cdata=True)
root = etree.XML('<root><x><![CDATA[<test>]]></x></root>', parser)
print etree.tostring(root)

for elem in root.findall('x'):
    elem.text = etree.CDATA(elem.text)
print etree.tostring(root)

Produces:

<root><x>&lt;test&gt;</x></root>
<root><x><![CDATA[<test>]]></x></root>