XPath: Fetch attribute of the parent node only if all child nodes have a specific value

I have the following XML document:

<root>
  <description name="testing1">
    <descriptionextension name="unda">
      <type>test</type>
    </descriptionextension>
    <descriptionextension name="koppu">
      <type>test</type>
    </descriptionextension>
    <descriptionextension name="valid">
      <type>test</type>
    </descriptionextension>
  </description>
  <description name="testing2">
    <descriptionextension name="valid">
      <type>test</type>
    </descriptionextension>
    <descriptionextension name="valid">
      <type>test</type>
    </descriptionextension>
    <descriptionextension name="valid">
      <type>test</type>
    </descriptionextension>
  </description>
</root>

This is an XPath request:

//description/descriptionextension[contains(@name,'valid')]/../@name

Is it possible to get a description name only if all child extension descriptions are "valid". Here I want to get only "testing2".

+4
source share
4 answers

One solution:

//description[empty(descriptionextension[@name != 'valid'])]/@name/string()

Here is another one (there are others):

//description[not(descriptionextension/@name != 'valid')]/@name/string()

Using XQuery you can write:

for $d in //description
where every $de in $d/descriptionextension satisfies $de/@name = 'valid'
return $d/@name/string()

As you can see, a descriptionwill also be accepted if it has no children descriptionextension.

+4
source

You can try to find all elements without any event other than "valid":

/root/description[count(descriptionextension[@name!="valid"])=0]/@name

, , ...

+1

Try the following:

string(//description[count(descriptionextension[@name="valid"]) = count(descriptionextension)]/@name)

Output:

testing2
+1
source

That should do the trick

//description[descriptionextention/@name='valid']/@name
-2
source

Source: https://habr.com/ru/post/1694657/


All Articles