4

I'm using the cElementTree module in Python to get the text child of an XML tree, using the text property. But it seems to work only for the immediate text children (see below).

$ python
...
>>> import xml.etree.cElementTree as ET
>>> root = ET.XML('<root><elm key="value">Some text</elm>More text</root>')
>>> root.text
>>> root = ET.XML('<root>Text 1<elm key="value">Text</elm>Text 2<elm2 />Text 3</root>')
>>> root.text
'Text 1'
>>>

Is it possible to retrieve all immediate text children of a given element (maybe as a list, i.e. ['More text'] and ['Text 1', 'Text 2', 'Text 3'] in the above examples) using the cElementTree module?

ZdaR
  • 22,343
  • 7
  • 66
  • 87
Sumit
  • 2,242
  • 1
  • 24
  • 37

1 Answers1

9

Use xml.etree.ElementTree.Element.itertext:

>>> import xml.etree.cElementTree as ET
>>> root = ET.XML('<root><elm key="value">Some text</elm>More text</root>')
>>> list(root.itertext())
['Some text', 'More text']
>>> root = ET.XML('<root>Text 1<elm key="value">Text</elm>Text 2<elm2 />Text 3</root>')
>>> list(root.itertext())
['Text 1', 'Text', 'Text 2', 'Text 3']

UPDATE

To get immediate text children, you also need to access tail of child nodes:

>>> root = ET.XML('<root><elm key="value">Some text</elm>More text</root>')
>>> ([root.text] if root.text else []) + [child.tail for child in root]
['More text']
>>> root = ET.XML('<root>Text 1<elm key="value">Text</elm>Text 2<elm2 />Text 3</root>')
>>> ([root.text] if root.text else []) + [child.tail for child in root]
['Text 1', 'Text 2', 'Text 3']
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • See my edit - I only want to retrieve the *immediate* text children, so the result is `['More text']` and `['Text 1', ''Text 2', 'Text 3']` for the two examples. – Sumit Dec 12 '15 at 14:28
  • @Sumit, Thank you for your feedback. I updated the answer accordingly. – falsetru Dec 12 '15 at 14:34