lasagne
lasagne

Reputation: 641

How to select a node based on its child's text value?

I want to select a node based on the text value of a child. My structure is as follows (sorry for german nodes):

<InspizierteAbwassertechnischeAnlage>           
  <Objektbezeichnung>10502002</Objektbezeichnung>
  <Anlagentyp>1</Anlagentyp>
</InspizierteAbwassertechnischeAnlage>

How can I select the <InspizierteAbwassertechnischeAnlage> node where e.g. <Objektbezeichnung> = 10502002?

Upvotes: 0

Views: 64

Answers (1)

toniedzwiedz
toniedzwiedz

Reputation: 18563

Why your solution didn't work

ancestor:://*[text()='10502002'] is syntactically incorrect, it's not valid XPath. I'm not sure what you tried to do with the axes here.

//*[text()='10502002'] itself would just select the Objektbezeichnung itself and not its parent. It would also select any other element with such a value, regardless of its name. In case of this document, nothing redundant would be returned but you have to be careful when using wildcards (*)

The solution

It's quite simple, you have to use a predicate to inspect the content of the child element

//InspizierteAbwassertechnischeAnlage[Objektbezeichnung = '10502002']

Note the double slash (// ), it is the abbreviated syntax for the descendant-or-self axis. The above expression translates to:

/descendant-or-self::InspizierteAbwassertechnischeAnlage[Objektbezeichnung = '10502002']

Or in plain English

In the set of all descendants of the document's root, find InspizierteAbwassertechnischeAnlage elements that contain at least one Objektbezeichnung element with a value of 10502002

As for German element names, at least it's not Hottentottenstottertrottelmutterbeutelrattenlattengitterkofferattentäter or Rhababerbarbarabarbarbarenbartbarbierbierbarbärbel

Upvotes: 1

Related Questions