Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Python ElementTree to Extract Text in XML Tag

Tags:

python

xml

I have a corpus with tens of thousands of XML file (small sized files) and I'm trying to use Python and extract the text contained in one of the XML tags, for example, everything between the body tags for something like:

<body> sample text here with <bold> nested </bold> tags in this paragraph </body>

and then write a text document that contains this string, and move on down the list of XML files.

I'm using effbot's ELementTree but couldn't find the right commands/syntax to do this. I found a website that uses miniDOM's dom.getElementsByTagName but I'm not sure what the corresponding method is for ElementTree. Any ideas would be greatly appreciated.

like image 587
Levar Avatar asked Mar 25 '26 04:03

Levar


1 Answers

I would just use re:

import re
body_txt = re.match('<body>(.*)</body>',body_txt).groups()[0]

then to remove the inner tags:

body_txt = re.sub('<.*?>','',body_txt)

You shouldn't use regexp when they are not needed, it's true... but there's nothing wrong with using them when they are.

like image 93
Scruffy Avatar answered Mar 27 '26 17:03

Scruffy



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!