S K
S K

Reputation: 335

Why won't my XPath work with mixed content?

In an HTML below:

   <html>
        <div class="row content-box">
        <div class="col-xs-12 col-sm-6">
        <div class="gray-separator-3">
        <div class="row to-top">
          <h2 class="xs-mt-0">
            Who's covered? 
            <span class="ns-i-pencil_icon icon-flipped pensil-font"></span>
            <span>
              <a class="edit-font firefinder-match" href="#">Edit</a>
            </span>
        </h2>
        <p class="xs-mt-0 xs-mb-0">David</p>
        </div>
        </div>
        </div>
  </html>

XPath for the 'Edit' Link doesn't seem to work when written as:

//div[.//h2[contains(.,'Who's covered?')]]//span/a[.='Edit']

but seems to work as expected when written as:

//div[.//h2]//span/a[.='Edit']

And works fine when there's no child node under <h2>

Like in the case below, when I write an XPath like this:

//div[.//h2[contains(.,'What's covered?')]]//span/a[.='Edit'] it identifies the element.

<html>
    <div class="row content-box">
    <div class="col-xs-12 col-sm-6">
    <div class="gray-separator-3">
    <div class="row to-top">
      <h2 class="xs-mt-0">
        What's covered?
      </h2>
      <span>
        <a class="edit-font firefinder-match" href="#">Edit</a>
      </span>
      <p class="xs-mt-0 xs-mb-0">David</p>
    </div>
    </div>
    </div>
</html>

Is there a reason why it doesn't read the <h2> which has child nodes under it along with the text?

Could anyone explain what the difference is when a node has both text and a subtree and a node which has only text but no subtree when writing an XPath?

Upvotes: 2

Views: 253

Answers (1)

kjhughes
kjhughes

Reputation: 111621

This has nothing to do with mixed vs non-mixed content.

Your first XPath is malformed. Change it from

//div[.//h2[contains(.,'Who's covered?')]]//span/a[.='Edit']

to

//div[.//h2[contains(.,"Who's covered?")]]//span/a[.='Edit']

and it will work as you expect.

Note that if the language hosting the XPath is already using " to surround the XPath itself, you should be able to escape the inner " as thus (for Java):

"//div[.//h2[contains(.,\"Who's covered?\")]]//span/a[.='Edit']"

And works fine when there's no child node under

No, that malformed XPath shouldn't work fine anywhere.

Upvotes: 3

Related Questions