Skip to content

gh-81055: Support CDATA sections in xml.etree.ElementTree - #156923

Draft
serhiy-storchaka wants to merge 1 commit into
python:mainfrom
serhiy-storchaka:gh-81055-cdata-str
Draft

gh-81055: Support CDATA sections in xml.etree.ElementTree#156923
serhiy-storchaka wants to merge 1 commit into
python:mainfrom
serhiy-storchaka:gh-81055-cdata-str

Conversation

@serhiy-storchaka

@serhiy-storchaka serhiy-storchaka commented Sep 4, 2026

Copy link
Copy Markdown
Member

An alternative to #156742: CDATA is a str subclass for character data which is serialized as a CDATA section, instead of a factory of special elements. It can be used as the text or the tail of an element:

elem.text = CDATA("<raw> & unescaped")

The content of a CDATA section is parsed as ordinary character data by default. If insert_cdata is true, TreeBuilder adds it to the tree as a CDATA string: as the text or the tail of an element if it is not set yet, and otherwise in a new element with the tag None. A section does not share the place with what follows it, so it is moved to such an element if character data or another section follows it.

Since the content is character data, it is a part of the inner text returned by itertext() and by the "text" serialization method, without any change in Element.

pyexpat exposes XML_SetCdataSectionHandler in its capsule, and _set_factories() takes the CDATA type as the third argument, so the C implementation supports this too.

CDATA is a str subclass for character data which is serialized as a CDATA
section.  It can be used as the text or the tail of an element.

The content of a CDATA section is parsed as ordinary character data by
default.  If insert_cdata is true, TreeBuilder adds it to the tree as a CDATA
string: as the text or the tail of an element if it is not set yet, and
otherwise in a new element with the tag None.  A section does not share the
place with what follows it, so it is moved to such an element if character
data or another section follows it.

The C implementation supports this too: pyexpat exposes
XML_SetCdataSectionHandler in its capsule, and _set_factories takes the CDATA
type as the third argument.
@read-the-docs-community

Copy link
Copy Markdown

Documentation build overview

📚 cpython-previews | 🛠️ Build #34389408 | 📁 Comparing d873716 against main (5f7d709)

  🔍 Preview build  

3 files changed
± library/xml.etree.elementtree.html
± whatsnew/3.16.html
± whatsnew/changelog.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant