使用 python 从 xml 数据中提取所有文本

Extract all the text from xml data with python

我是 xml 数据处理的新手。我想提取以下 xml 文件中的文本数据:

<data>
    <p>12345<strong>45667</strong>abcde</p>
</data>

所以预期的结果是: ['12345','45667', 'abcde']目前我已经尝试过:

tree = ET.parse('data.xml')
data = tree.getiterator()
text = [data[i].text for i in range(0, len(data))]

但结果只显示 ['12345','45667']'abcde' 丢失。有人能帮我吗?提前致谢!

尝试使用 and 执行此操作:

import lxml.etree as etree

string = '''
<data>
    <p>12345<strong>45667</strong>abcde</p>
</data>
'''

tree = etree.fromstring(string)

print(tree.xpath('//p//text()'))

Xpath 表达式的意思是:"select all p elements wich containing text recursively"

输出:

['12345', '45667', 'abcde']

getiterator()(或者它是 strong 标签的替换 iter()) iterates over child tags/elements, while abcde is a text node, a tail

可以使用itertext()方法:

import xml.etree.ElementTree as ET

tree = ET.parse('test.xml')
print list(tree.find('p').itertext())

打印:

['12345', '45667', 'abcde']