tags:

views:

419

answers:

1

I want there to be CDATA sections in my output XML. I have tried to use the "cdata-sections-element" attribute of xsl:output. However, I don't get CDATA in my output.

using System;
using System.Xml;
using System.Xml.Xsl;
using System.IO;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string stylesheet =
@"<xsl:stylesheet version=""1.0"" xmlns:xsl=""http://www.w3.org/1999/XSL/Transform""&gt;
<xsl:output xmlns:t=""temp-uri"" cdata-section-elements=""t:text"" method=""xml""/>
<xsl:template match=""/"">
<text xmlns=""temp-uri""><xsl:value-of select="".""/></text>
</xsl:template>
</xsl:stylesheet>
";
            XmlReader reader = XmlReader.Create(new StringReader(stylesheet));
            XslCompiledTransform t = new XslCompiledTransform(true);
            t.Load(reader);

            XmlReader input = XmlReader.Create(new StringReader("<foo><![CDATA[<hello]]></foo>"));
            StringBuilder sb = new StringBuilder();

            XmlWriter results = XmlWriter.Create(new StringWriter(sb));
            t.Transform(input, null, results);

            Console.WriteLine(sb.ToString());
            Console.ReadLine();
        }
    }
}

Actual output

 <?xml version="1.0" encoding="utf-16"?><text xmlns="temp-uri">&lt;hello</text>

Required output

<?xml version="1.0" encoding="utf-16"?><text xmlns="temp-uri"><!CDATA[<hello]]></text>

What am I missing here?

+2  A: 

Your XmlWriter has to be informed about the current output settings:

XmlWriter results = XmlWriter.Create(new StringWriter(sb), t.OutputSettings);
//---------------------------------------------------------^^^^^^^^^^^^^^^^
Tomalak