Skip to content

Commit 98a9ccb

Browse files
[3.13] gh-149571: Fix the C implementation of Element.itertext() (GH-149929) (GH-150511)
It no longer emits text for comments and processing instructions. (cherry picked from commit 7de4fcd) Co-authored-by: Serhiy Storchaka <storchaka@gmail.com>
1 parent 43f71b0 commit 98a9ccb

3 files changed

Lines changed: 32 additions & 0 deletions

File tree

Lib/test/test_xml_etree.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3553,6 +3553,32 @@ def test_basic(self):
35533553
doc = ET.XML("<root>a&amp;<sub>b&amp;</sub>c&amp;</root>")
35543554
self.assertEqual(''.join(doc.itertext()), 'a&b&c&')
35553555

3556+
def test_comment(self):
3557+
e = ET.Element('root')
3558+
e.text = 'before'
3559+
comment = ET.Comment('comment')
3560+
self.assertEqual(comment.text, 'comment')
3561+
comment.tail = 'after'
3562+
e.append(comment)
3563+
self.assertEqual(''.join(e.itertext()), 'beforeafter')
3564+
self.assertEqual(list(e.iter()), [e, comment])
3565+
self.assertEqual(list(e.iter('root')), [e])
3566+
self.assertEqual(''.join(comment.itertext()), '')
3567+
self.assertEqual(list(comment.iter()), [comment])
3568+
3569+
def test_processinginstruction(self):
3570+
e = ET.Element('root')
3571+
e.text = 'before'
3572+
pi = ET.PI('test', 'instruction')
3573+
self.assertEqual(pi.text, 'test instruction')
3574+
pi.tail = 'after'
3575+
e.append(pi)
3576+
self.assertEqual(''.join(e.itertext()), 'beforeafter')
3577+
self.assertEqual(list(e.iter()), [e, pi])
3578+
self.assertEqual(list(e.iter('root')), [e])
3579+
self.assertEqual(''.join(pi.itertext()), '')
3580+
self.assertEqual(list(pi.iter()), [pi])
3581+
35563582
def test_corners(self):
35573583
# single root, no subelements
35583584
a = ET.Element('a')
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix the C implementation of :meth:`xml.etree.ElementTree.Element.itertext`:
2+
it no longer emits text for comments and processing instructions.

Modules/_elementtree.c

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2264,6 +2264,10 @@ elementiter_next(ElementIterObject *it)
22642264
return NULL;
22652265
}
22662266
if (it->gettext) {
2267+
if (elem->tag != Py_None && !PyUnicode_Check(elem->tag)) {
2268+
Py_DECREF(elem);
2269+
continue;
2270+
}
22672271
text = element_get_text(elem);
22682272
goto gettext;
22692273
}

0 commit comments

Comments
 (0)