I have a problem with establishing a dependency without redundancy in XSLT 1.0. I have a node type a, and a node type b. a is dependent on b – if I encounter an a, and there is not a b already present, I should insert one. Furthermore, I shouldn’t change anything in any other situation.
Input:
<variables>
<var Value="a"/>
</variables>
Output:
<variables>
<var Value="a"/>
<var Value="b"/>
</variables>
The difficulty I’m having is that I don’t know how to search for a and b inside the same template. I can search for a, and replace it with a and b, but then I find myself with a redundancy when both were there in the first place. I can search for a or b, and replace the first instance of that with a and b, but then if I only have b, I’ll be including a without wanting to. I don’t know how to search for a, and then, if I find it, search for a peer-level node b.
This transformation:
when applied on the provided XML document:
produces the wanted, correct result:
Explanation:
The identity rule/template copies every node “as-is”. Using and overriding the identity rule is the most fundamental and powerful XSLT design pattern.
There is just one more template — overriding the identity rule for any
varelement the value of whoseValueattribute is"a"that doesn’t have a siblingvarelement withValueattribute with value"b". This template copies its matching element and then creates a newvarelement as required.