Home > Blockchain >  xpath query to check if all xml element have same value
xpath query to check if all xml element have same value

Time:10-04

I have the following xml

<collection>
<item>
    <id>001</id>
    <attributes>
        <attr1>A</attr1>
    </attributes>
</item>
<item>
    <id>002</id>
    <attributes>
        <attr1>A</attr1>
    </attributes>
</item>
<item>
    <id>003</id>
    <attributes>
        <attr1>B</attr1>
    </attributes>
</item>
</collection>

I need my xpath query to return me "true" if all attr1='A'. I tried with this but it returns "true" even if only one attr1="A".

//item/attr1/text()='A'

CodePudding user response:

Your current XPath is returning true because there is at least one attr1 element that has a text() value of A.

You could test whether the count of attr1 elements is equal to the count of attr1 elements that have text() with the value A:

count(//item/attr1) = count(//item/attr1[text() = 'A'])

Or you could evaluate an expression to test that there are not() any attr1 elements that are not equal to A:

not(//item/attr1[not(text() = 'A')])

CodePudding user response:

You can get the text value of the first node with attr1 and then to search for nodes with attr1 with text not equals to that text value:

textValue = //item/attr1/text()
//item/attr1[not(text() = textValue)]
  • Related