Lxml Xpath Expression For Selecting All Text Under A Given Child Node Including His Children
Provided I have a XML as follows:
Solution 1:
Try using either string()
or normalize-space()
...
from lxml import etree
XML_content = """
<node1>
<text title='book'>
<div chapter='0'>
<div id='theNode'>
<p xml:id="x40">
A House that has:
<p xml:id="x45">- a window;</p>
<p xml:id="x46">- a door</p>
<p xml:id="x47">- a door</p>
its a beuatiful house
</p>
</div>
</div>
</text>
</node1>
"""
XML_tree = etree.fromstring(XML_content)
text = XML_tree.xpath('string(//text[@title="book"]/div/div/p)')
# text = XML_tree.xpath('normalize-space(//text[@title="book"]/div/div/p)')print(text)
Output using string()
...
A House that has:
- a window;
- a door
- a door
its a beuatiful house
Output using normalize-space()
...
A House that has: - a window; - a door - a door its a beuatiful house
Solution 2:
Another option :
XML_tree = etree.fromstring(XML_content)
text = [el.strip() for el in XML_tree.xpath('//text()[ancestor::text[@title="book"]][normalize-space()]')]
print(" ".join(text))
print("\n".join(text))
Output :
A House that has: - a window; - a door - a door its a beuatiful house
A House that has:
- a window;
- a door
- a door
its a beuatiful house
Post a Comment for "Lxml Xpath Expression For Selecting All Text Under A Given Child Node Including His Children"