Skip to content

gh-68475: Keep comments and processing instructions outside the root element - #156719

Open
serhiy-storchaka wants to merge 2 commits into
python:mainfrom
serhiy-storchaka:gh-68475-document-children
Open

gh-68475: Keep comments and processing instructions outside the root element#156719
serhiy-storchaka wants to merge 2 commits into
python:mainfrom
serhiy-storchaka:gh-68475-document-children

Conversation

@serhiy-storchaka

@serhiy-storchaka serhiy-storchaka commented Aug 31, 2026

Copy link
Copy Markdown
Member

ElementTree now has a children attribute: a view of the children of the document, containing the root element and any number of comments and processing instructions around it. Adding a second element is an error.

TreeBuilder no longer discards the comments and processing instructions which occur outside the root element, and returns them, together with the root element, from the new document() method. This only happens when insert_comments or insert_pis is true, so nothing changes for existing code.

ElementTree.iter() now iterates over all children of the document. find(), findall() and iterfind() still search from the root element.

A view which validates its content when modified follows @scoder's suggestion above, rather than the originally proposed ElementTree.append(), whose name @vadmium and @scoder both objected to. It covers the epilog as well as the prolog.

… root element

ElementTree gets the children attribute, a view of the children of the
document, containing the root element and any number of comments and
processing instructions around it.  Adding a second element is an error.
iter() iterates over all of them, but find(), findall() and iterfind()
still search from the root element.

TreeBuilder collects the comments and processing instructions which occur
outside the root element and returns them, together with the root element,
from the new document() method.  This only happens when insert_comments or
insert_pis is set, so nothing changes for existing code.  parse() asks the
target for the document before close(), which releases it.

The C accelerator implements document() too, so that the feature works at
full parsing speed.
@read-the-docs-community

read-the-docs-community Bot commented Aug 31, 2026

Copy link
Copy Markdown

Documentation build overview

📚 cpython-previews | 🛠️ Build #34315170 | 📁 Comparing abb469f against main (d87ee27)

  🔍 Preview build  

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

Registering the implementation with a cast is a call through a pointer to
an incorrect function type: it is warned about by the compiler, reported by
UBSan, and traps on WASI.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant