Tezyn
Tezyn

Reputation: 1344

Why is //element selecting too many elements in XPath?

I am working on a project where I need to be able to transform an XML document, and need to be able to identify the Name of the Opportunity, but the xpath expression //Name returns the Name of the Owner and the Name of the Opportunity.

Demo

Example XML:

  <root xmlns:foo="http://www.foo.org/" xmlns:bar="http://www.bar.org">
    <Opportunity>
      <Owner>
        <Name>Christian Bale</Name>
      </Owner>
      <Name>Opportunity Name</Name>
    </Opportunity>
  </root>

I can't seem to find a predicate that will only return the name of the opportunity. Because both are the last Name element at their level, //Name[last()] and //Name[1] still returns both.

Is it possible to write an XPath expression that only returns the Name of the Opportunity and not the name of the Opportunity Owner? Or is it possible to eliminate one of the matching notes after it has been selected?

Upvotes: 1

Views: 62

Answers (2)

kjhughes
kjhughes

Reputation: 111726

Understand that // selects descendants (or self), so it skips heritage by design. To specify heritage, use /, which selects along the child axis by default:

/root/Opportunity/Name

is then separately selectable from

/root/Opportunity/Owner/Name

as requested.

Upvotes: 2

LMC
LMC

Reputation: 12822

Just use

//Opportunity/Name/text()

Upvotes: 1

Related Questions