Skip to content

ElementTree: itertext() and tostring(method="text") lose the text of elements whose tag is a QName #161809

Open

Description

@ines-besrour

Bug report

Bug description

Element.itertext(), and therefore tostring(..., method="text"), skips elements whose tag is not a str, in order to leave out comments and processing instructions. The same check also matches QName tags, so their text disappears, even though the tree serializes to XML with all of its text:

import xml.etree.ElementTree as ET

root = ET.Element(ET.QName("http://example.com/ns", "doc"))
root.text = "hello "
b = ET.SubElement(root, "b"); b.text = "world"; b.tail = "!"
i = ET.SubElement(root, ET.QName("http://example.com/ns", "i")); i.text = "QTEXT"

ET.tostring(root, encoding="unicode")
# '<ns0:doc xmlns:ns0="http://example.com/ns">hello <b>world</b>!<ns0:i>QTEXT</ns0:i></ns0:doc>'
list(root.itertext())
list(root.itertext()) C accelerator pure Python
3.12.16 ['hello ', 'world', '!', 'QTEXT'] []
3.13.18, 3.14.10 ['world', '!'] []

tostring(root, method="text", encoding="unicode") gives 'hello world!QTEXT' with C on 3.12, 'world!' with C on 3.13 and 3.14, and '' with the pure-Python implementation.

Cause. Both implementations skip on "tag is not a str": Python has if not isinstance(tag, str) and tag is not None: return in Element.itertext(), and C has if (elem->tag != Py_None && !PyUnicode_Check(elem->tag)) in elementiter_next(). The C check came with the fix for gh-149571 (GH-149929), which made C skip comments and processing instructions like Python does; QName tags were not considered there. That is why C on 3.13 and 3.14 now drops the text of QName elements. It still yields their children's text and tails, while Python returns nothing for the whole subtree.

CPython versions tested on:

3.12, 3.13, 3.14, CPython main branch

Operating systems tested on:

No response

Activity

  1. added
    stdlibStandard Library Python modules in the Lib/ directory
    on Nov 11, 2026
  2. picnixz commented on Nov 11, 2026

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    extension-modulesC modules in the Modules dirstdlibStandard Library Python modules in the Lib/ directorytopic-XMLtype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions