How can I get a text with no tag in xml file by python

Viewed 700
<?xml version='1.0' encoding='UTF-8'?>
<GateDocument>
<!-- The document content area with serialized nodes -->

<TextWithNodes><Node id="0" />Norway<Node id="6" /> <Node id="7" 
/>to<Node id="9" /> <Node id="10" />'<Node id="11" />completely<Node 
id="21" /> <Node id="22" />ban<Node id="25" /> <Node id="26" 
/>petrol<Node id="32" /> <Node id="33" />powered<Node id="40" /> <Node 
id="41" />cars<Node id="45" /> <Node id="46" />by<Node id="48" /> <Node 
id="49" />2025<Node id="53" />'<Node id="54" />.<Node id="55" /> . 
</TextWithNodes>
</GateDocument>

From the above XML file, you can notice that the words in "TextWithNodes" tag have no tags. How could I get for example "petrol powered cars" text by python

Thank you

1 Answers

You can use the itertext() method after you find the node you want with findall():

from xml.etree import ElementTree as ET
x = '''<?xml version='1.0' encoding='UTF-8'?>
<GateDocument>
<!-- The document content area with serialized nodes -->

<TextWithNodes><Node id="0" />Norway<Node id="6" /> <Node id="7"
/>to<Node id="9" /> <Node id="10" />'<Node id="11" />completely<Node
id="21" /> <Node id="22" />ban<Node id="25" /> <Node id="26"
/>petrol<Node id="32" /> <Node id="33" />powered<Node id="40" /> <Node
id="41" />cars<Node id="45" /> <Node id="46" />by<Node id="48" /> <Node
id="49" />2025<Node id="53" />'<Node id="54" />.<Node id="55" /> .
</TextWithNodes>
</GateDocument>'''
t = ET.fromstring(x)
print(''.join(t.findall('.//TextWithNodes')[0].itertext()))

This outputs:

Norway to 'completely ban petrol powered cars by 2025'. .
Related