senleft
senleft

Reputation: 511

How to prevent adding the empty CDATA elements?

The below is used XSLT and input/output XML. The output XML contains the empty CDATA elements. How to prevent adding it without excluding from cdata-section-elements? XSLT

    <?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
    <xsl:output cdata-section-elements="first second" indent="yes"/>
    <xsl:strip-space elements="first second"/>
    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

Input

    <?xml version="1.0" encoding="UTF-8"?>
<top>
    <first>
        <second/>
    </first>
    <first>
        <second><![CDATA[! Please note...]]></second>
    </first>
</top>

Output with strip-space

    <?xml version="1.0" encoding="UTF-8"?>
<top>
    <first>
      <second/>
   </first>
    <first>
      <second><![CDATA[! Please note...]]></second>
   </first>
</top>

Output without strip-space

<?xml version="1.0" encoding="UTF-8"?>
<top>
    <first><![CDATA[
        ]]><second/><![CDATA[
    ]]></first>
    <first><![CDATA[
        ]]><second><![CDATA[! Please note...]]></second><![CDATA[
    ]]></first>
</top>

Upvotes: 2

Views: 679

Answers (2)

michael.hor257k
michael.hor257k

Reputation: 117140

I would suggest you try it this way:

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

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

</xsl:stylesheet>

Although I don't quite see the point of this exercise, as the output is identical to the input - both semantically and lexically (except possibly the amount of indent).

Upvotes: 0

uL1
uL1

Reputation: 2167

Keyword to the solution is function strip-space. Go ahead with:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

    <xsl:output cdata-section-elements="first"/>
    <xsl:strip-space elements="first second"/>
    ...

To be precise there are whitespace-text nodes between these two nodes:

<first>
    <second/>

The CDATA can't ignore these whitespaces, otherwise it would change the content. So you have to command the processor, what to do with these text-nodes.


Second possible solution: You address the whitespace-text via template and remove them:

<xsl:template match="first/text()[not(normalize-space())]"/>

Upvotes: 1

Related Questions