Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract all the text from xml data with python

I'm new to xml data processing. I want to extract the text data in the following xml file:

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

so that expected result is: ['12345','45667', 'abcde'] Currently I have tried:

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

But the result only shows ['12345','45667'] . 'abcde' is missing. Can someone help me? Thanks in advance!

like image 230
Xueqing Liu Avatar asked Aug 02 '26 05:08

Xueqing Liu


1 Answers

Try doing this using xpath and lxml :

import lxml.etree as etree

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

tree = etree.fromstring(string)

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

The Xpath expression means: "select all p elements wich containing text recursively"

OUTPUT:

['12345', '45667', 'abcde']
like image 149
Gilles Quenot Avatar answered Aug 03 '26 20:08

Gilles Quenot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!