Search code examples
c#xsltcdata

Add CDATA to a Node Value in a loop


** Updated the output ** I am trying to add a <![CDATA[...]] to a value node that is being generated inside a loop. I am using XSLT & C#.net. I have tried a couple of things including Add CDATA to an xml file but none seems to be working so far. I even tried adding it literally but, as expected it did not work out. Can anyone please help me in this.

Here's how my node is being generated

<xsl:for-each select="$OLifE/">
                    <DataPoint>
                      <Name>Carrier.Requirements<xsl:if test="$NumberOfPayments > 1"><xsl:value-of select="position()"/></xsl:if></Name>
                      <Value>Here is the response text</Value>
</DataPoint>

My expected output is

<DataPoint>
    <Name>Carrier.Requirements1</Name>
    <Value><![CDATA[Here is the response text]]</Value>
</DataPoint>
<DataPoint>
    <Name>Carrier.Requirements2</Name>
    <Value><![CDATA[Here is the response text]]</Value>
</DataPoint>
<DataPoint>
    <Name>Carrier.Requirements3</Name>
    <Value><![CDATA[Here is the response text]]</Value>
</DataPoint>

Please let me know in case any further information is required.


Solution

  • Here is a simplified example:

    XML

    <input>
        <item/>
        <item/>
        <item/>
    </input>
    

    XSLT 1.0

    <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" cdata-section-elements="Value"/>
    <xsl:strip-space elements="*"/>
    
    <xsl:template match="/input">
        <output>
            <xsl:for-each select="item">
                <DataPoint>
                    <Name>
                        <xsl:value-of select="concat('Carrier.Requirements', position())"/>
                    </Name>
                    <Value>Here is the response text</Value>
                </DataPoint>
            </xsl:for-each>
        </output>
    </xsl:template>
    
    </xsl:stylesheet>
    

    Result

    <?xml version="1.0" encoding="utf-16"?>
    <output>
      <DataPoint>
        <Name>Carrier.Requirements1</Name>
        <Value><![CDATA[Here is the response text]]></Value>
      </DataPoint>
      <DataPoint>
        <Name>Carrier.Requirements2</Name>
        <Value><![CDATA[Here is the response text]]></Value>
      </DataPoint>
      <DataPoint>
        <Name>Carrier.Requirements3</Name>
        <Value><![CDATA[Here is the response text]]></Value>
      </DataPoint>
    </output>
    

    Demo: https://xsltfiddle.liberty-development.net/94hvTAn