I have an xml like, values can be
<n1>value1</n1>
<n1>value1</n1>
<n1>value2</n1>
I need to check if all these values are same and if same I would need to assign it to another element. I am using XSLT v1.0.
Thanks,
I have an xml like, values can be
<n1>value1</n1>
<n1>value1</n1>
<n1>value2</n1>
I need to check if all these values are same and if same I would need to assign it to another element. I am using XSLT v1.0.
Thanks,
Good question, +1.
Just use:
Assuming that all
n1
elements are selected in a variable named$v
, this can be expressed in just 14 characters-long XPath expression:Explanation 1:
By definition:
is
true()
exactly if there exists a node in/*/n1
whose string value isn't equal to the string value of/*/n1[1]
The logical negation of this:
is
true()
iff no node in/*/n1
exists whose string value isn't equal to the string value of/*/n1[1]
-- that is, if all nodes in/*/n1
have the same sting value.Explanation 2:
This follows from a more general double negation law :
is equivalent to:
Assume a document of this form:
The following simple stylesheet determines whether every
n1
element has the same value:Output:
The key to this stylesheet is the expression:
...which compares the count of the
n1
elements whose value equals the value of the firstn1
element to the count of alln1
elements. These counts will be equal only when everyn1
node has the same value.This can be made a little easier to read by first selecting all
n1
into a variable namedn
:Conditionally perform some action based on the result like this: