1

For this HTML / XML:

<div class="contentBlock">
  <h2> </h2>
  <h1></h1>
  <h1>DBS055 - single  module packages</h1>
</div>

I want to extract with XPath only DBS055, not the entire text.

1 Answer 1

0

XPath 2.0

//h1[normalize-space()]/replace(normalize-space(),'^([\w\-]+).*', '$1')

will return all of the first words of the string values of those h1 elements that have a non-space character in their string value.

XPath 1.0

substring-before(
  concat(
    normalize-space(
      translate(//h1[normalize-space()][1], ',;/.', ' ')), ' '), ' ')

approximates the more robust XPath 2.0 solution. Expand ',;/.' as necessary for various characters you consider to define word boundaries.

Explanation:

  1. Select the first h1 that has a non-whitespace-only string value.
  2. Map all word boundary characters to spaces.
  3. Append a space to cover single-word case.
  4. Normalize spacing.
  5. Return the substring before the first space.
6
  • it should not be h1[2]? the path igives me a result, but space only:( Commented Apr 26, 2021 at 14:42
  • No, the [1] is applied after the predicate, and you don't want to hardwire a 2 that would be data-dependent. I've updated the XPaths to avoid any h1 elements with white-space-only string values. That should be more robust for you.
    – kjhughes
    Commented Apr 26, 2021 at 14:54
  • Thanks it works perfectly, if possible can you tell me where to look to learn these kinds of xpath statements, or some tutorials with explanations ? Commented Apr 27, 2021 at 6:41
  • I just ancountered a situation were : <div class="contentBlock"> <h2> </h2> <h1></h1> <h1>DBS055 - single module packages</h1> </div <div class="contentBlock"> <h2> </h2> <h1></h1> <h1>DBS055, - single module packages</h1> </div for example in the second part i have a ",", after DBS055, can i have a unique xpath for both cases? Commented Apr 27, 2021 at 6:48
  • Answer updated to make XPath 1.0 expression much more robust, including covering your new case that requires expansion of word boundary characters beyond just spaces.
    – kjhughes
    Commented Apr 27, 2021 at 11:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.