Today I was introduced a problem with an old technology XSLT. 🙂
I realized that I forgot all about XSLT because I wasn’t coding with XML and XSLT since JSON is a thing. I think it was around 2008-2010.
The problem is;
– We have 2 nodes that customer can use. defaultX, defaultY
– If the XML has these nodes, use their value in output.
– If those are missing, introduce a default value.
There is no find, copy, delete methods in XSLT like a coding language so we need to make a work around.
Basically XSLT is all about using templates within templates right?
Here we go.
First you gotta have an identity template. That’s everyone agrees on.
What an identity template does is, copy everything from xml into your output.
It looks like this;
<xsl:template match=”@*|node()”><xsl:copy><xsl:apply-templates select=”@*|node()”/></xsl:copy></xsl:template>
Then you have to have another template just runs in the apply-templates of previous one.
<xsl:template match=”/*”><xsl:copy><xsl:apply-templates /><xsl:if test=”count(defaultx) = 0″><defaultx>||| DEFAULT VALUE FOR X |||</defaultx></xsl:if><xsl:if test=”count(defaulty) = 0″><defaulty>||| DEFAULT VALUE FOR Y |||</defaulty></xsl:if></xsl:copy></xsl:template>
What am I doing above is matching all items in root and copying them all again into my new output. While I’m doing this, I am testing the counts for defaultx tag. If the count is zero, it means in the previous output this tag does not exists. I am adding my own defaultx tag. Doing it for the defaulty tag.
So XML and XSLT is not dead yet. For micro services and web development we use mostly JSON but for old school banking and windows apps we still use XML files. (Linux apps is another story they have mostly JSON and their config file style which I love)
Now there are plenty resources out there but it took me almost 1 day to come back to it. So here is a small solution that might help you someday.
You can download this small example from my gist repo.
Cheers all and happy coding.