Extract text between tags with XPath including markup

python, xpath

Solution

To get any child node you can use:

/span[@class="st"]/node()

This will return:

- Two child text nodes

- The full `<em>` node (element and contents).

If you actually want all the `text()` nodes, including the ones inside `em`, then get all the `text()` descendants:

/span[@class="st"]//text()

or

/span[@class="st"]/descendant::text()

This will return three text nodes, the text inside `<em>`, but not the `<em>` elements.

Problem

I have the following piece of XML: ``` ...<span class="st">In Tim <em>Power</em>: Politieman...</span>... ``` I want to extract the part between the `<span>` tags. For this I use XPath: ``` /span[@class="st"] ``` This however will extract everything including the `<span>`. and. ``` /span[@class="st"]/text() ``` will return a list of two text elements. One containing "In Tim". The other ":Politieman". The `<em>..</em>` is not included and is handled like a separator. Is there a pure XPath solution which returns: ``` In Tim <em>Power</em>: Politieman... ``` EDIT Thanks to @helderdarocha and @TextGeek. Seems non trivial to extract plain text with XPath only including the `<em>`. The /span[@class="st"]/node() solution creates a list containing the individual lines, from which it is trivial in Python to create a String.

Original source