问题
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