Skip to content Skip to sidebar Skip to footer

Extract All Text In Body/p Tag

My main task is to extract all text in p tag in body tag in the following XML file named 'sample.xml':

Solution 1:

To get all the text of the p elements (including Person subelements and their .tails), use itertext().

from xml.etree import ElementTree as ET
 
tree = ET.parse('sample.xml')
 
for p in tree.findall(".//p"):
    # Get all inner text print("".join(t for t in p.itertext()))
 
    # Get the 'codej' attribute value (None if it does not exist)print(p.get("codej"))

Output:

Toiselle kierrokselle mennään, mikäli yksikään ehdokas ei ole saanut yli puolta ensimmäisellä kierroksella annetuista äänistä.
None
Vaaleissa ovat ehdokkaina Tuula Haatainen (sd.), Pekka Haavisto (vihr.), Laura Huhtasaari 
None
Varsinaisena vaalipäivänä vaalihuoneistot ovat auki tuttuun tapaan kello 9:n ja 20:n välisenä aikana. Tällöin on äänestettävä siinä paikassa, joka kotiin jaettuun äänestyskorttiin on merkitty. Osa äänestäjistä sai kortin kotiinsa jo ennen joulua.
obj:57654

Solution 2:

getroot() returns a single element, it's findall() that returns a list, so you sould iterate over that instead. Also, I'm not sure why findall('p') doesn't find what you want, but the xpath expression './/p' certainly does, try this:

from xml.etree import cElementTree as ET
tree = ET.parse('sample.xml')
root = tree.getroot()
for teksMain in root.findall('.//p'):
    print('main body:', teksMain.text)

Post a Comment for "Extract All Text In Body/p Tag"