How to get all text children of an element in cElementTree?

二次信任 提交于 2021-01-27 12:22:01

问题


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?


回答1:


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']


来源:https://stackoverflow.com/questions/34240818/how-to-get-all-text-children-of-an-element-in-celementtree

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!