I’ve got a xml document, looking like this:
<p>
<c1 />
<c2 />
</p>
The child elements c1 and c2 are optional, but for a processing step I need them to be existent. So I am trying to create a xslt stylesheet to add them as empty elements (the order of the children does not matter).
Here is my stylesheet:
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="p[not(c1)]">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
<c1 />
</xsl:copy>
</xsl:template>
<xsl:template match="p[not(c2)]">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
<c2 />
</xsl:copy>
</xsl:template>
This works fine, as long as only one of the child elements is missing. But if both are missing, only c1 is created. How do I prevent that and force the creation of both c1 and c2 (and in reality, of about 10 children)?
Thanks.
Jost
I would do it like this:
If you have a longer list of possible child nodes you can put them in a variable and use a
for-eachinstead than individualif:just add all the elements you need in the
childrenFragmentvariable.(the
msxsl:node-setstuff is Microsoft-specific, if you are using another XSLT processor you’ll need something slightly different)