Establishing a dependency in xslt
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:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="node()|@*" name="identity">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match=
"var[@Value='a' and not(../var[@Value='b'])]">
<xsl:call-template name="identity"/>
<var Value="b"/>
</xsl:template>
</xsl:stylesheet>
when applied on the provided XML document:
<variables>
<var Value="a"/>
</variables>
produces the wanted, correct result:
<variables>
<var Value="a"/>
<var Value="b"/>
</variables>
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
var
element the value of whoseValue
attribute is"a"
that doesn't have a siblingvar
element withValue
attribute with value"b"
. This template copies its matching element and then creates a newvar
element as required.
精彩评论