I have XML that gets values from user input. I want to test to see if the url node is blank.
If it is blank
- then I want to insert a value into a href
If it is not blank
- I want to use the node's value in the href
I have the following code but it is not working. What am I doing wrong?
<xsl:choose>
<xsl:when test="(url = '')">
<a href="https://example.com">
</xsl:when>
<xsl:otherwise>
<a href="{url}">
</xsl:otherwise>
</xsl:choose>
<h3><xsl:value-of select="level"></h3>
<h4><xsl:value-of select="name"></h4>
<h5><xsl:value-of select="location"></h5>
</a>
Here is an example of my XML
<unique-component-name>
<card>
<url></url>
<level>Level Value</level>
<name>Name Value</name>
<location>Location Value</name>
</card>
</unique-component-name>
If the user leaves the url blank I want the href to link to "https://example.com"
If the user provides a url I want the href to link to the user given url.
CodePudding user response:
I have the following code but it is not working. What am I doing wrong?
'Not working" is not a good description of a problem. You need to tell us how it fails. At this point, all we can say is that your XSLT code is not well-formed XML. You haven't closed the a
elements. Instead of:
<xsl:choose>
<xsl:when test="(url = '')">
<a href="https://example.com">
</xsl:when>
<xsl:otherwise>
<a href="{url}">
</xsl:otherwise>
</xsl:choose>
it needs to be:
<xsl:choose>
<xsl:when test="(url = '')">
<a href="https://example.com"/>
</xsl:when>
<xsl:otherwise>
<a href="{url}"/>
</xsl:otherwise>
</xsl:choose>
And of course you must get rid of the orphaned </a>
closing tag at the end.
Note also that the input XML is also not well-formed:
<location>Location Value</name>
CodePudding user response:
This would be a way to build an a
element and conditionally set href
attribute
<xsl:element name="a">
<xsl:choose>
<xsl:when test="(url = '')">
<xsl:attribute name="href">https://example.com</xsl:attribute>
</xsl:when>
<xsl:otherwise>
<xsl:attribute name="href"><xsl:value-of select="url"/></xsl:attribute>
</xsl:otherwise>
</xsl:choose>
<h3><xsl:value-of select="level"/></h3>
<h4><xsl:value-of select="name"/></h4>
<h5><xsl:value-of select="location"/></h5>
</xsl:element>