user3568194
user3568194

Reputation: 3

self closing tags issue on XSLT

I am using bellow XSLT syntax to select some values in my XML file and create a different version of XML file,

<xsl:element name="FirstName">
  <xsl:value-of select="//Invoice//FirstName"/>
</xsl:element> 

Problem i am having here is when there is any empty values within my XML , my out put XML generates like below

<Invoice>
 <FirstName /> 
</Invoice>

I wanted to generate my XML file like below when there is an empty value

<Invoice>
 <FirstName>   </FirstName> 
</Invoice>

how do i do this in XSLT ? thanks

Upvotes: 0

Views: 2367

Answers (2)

user663031
user663031

Reputation:

You could output a comment, as in

<xsl:comment/><xsl:value-of select="//Inoivce/FirstName"/>

This will result in output such as

<FirstName><!-- --></FirstName>

which should work just fine downstream.

This technique is sometimes used to force script tags to be non-closing, as they need to be:

<script src="foo.js"><xsl:comment/></script>

Upvotes: 3

Rudramuni TP
Rudramuni TP

Reputation: 1278

Try this:

XML:

<root>
<name>
<FirstName>Kishan</FirstName>
<LastName>Kumar</LastName>
</name>

<name>
<FirstName></FirstName>
<LastName>Raj</LastName>
</name>
 </root>

XSLT:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="node()|@*">
    <xsl:copy><xsl:apply-templates select="node()|@*"/></xsl:copy>
</xsl:template>

<xsl:template match="FirstName">
    <xsl:choose>
        <xsl:when test="string-length(.) &gt; 0">
            <xsl:element name="FirstName">
                      <xsl:value-of select="."/>
            </xsl:element>
        </xsl:when>
        <xsl:otherwise>
            <xsl:element name="FirstName">
                      <xsl:text> </xsl:text>
            </xsl:element>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

</xsl:stylesheet>

OutPut:

    <?xml version="1.0" encoding="UTF-8"?>
<root>
   <name>
      <FirstName>Kishan</FirstName>
      <LastName>Kumar</LastName>
   </name>
   <name>
      <FirstName> </FirstName>
      <LastName>Raj</LastName>
   </name>
</root>

Upvotes: -1

Related Questions