posts - 18, comments - 23, trackbacks - 1

My Links

News

This blog has moved to http://shailen.sukul.org

Article Categories

Archives

Post Categories

Monday, November 27, 2006

CData sections not appearing with XML Transform ( XSLT ) ( applies to XslCompiledTransform class )

I have noticed an anamoly with doing XML Transformations in .Net. If the XSLT marks specific sections as CDATA, the output seems to missing that.  

Example:

XSLT:

<xsl:output method="xml" omit-xml-declaration="yes" encoding="UTF-8" indent="yes" cdata-section-elements="EMPLAST EMPFIRST"/>

 

We would expect output to be of the format:

<Employee>

<EMPLAST><![CDATA[John]]></EMPLAST>

and so on...

</Employee>

However, the standard XSLT transformation does not output the CDATA bit, when done through .Net, so what you get is

<EMPLAST>John</EMPLAST>

This because the default example on MSDN uses an XmlWriter that will, guess what, write the xml text as, well ... xml and hence ignore the CDATA sections!! To properly write out the transformed text, use a TextWriter and all will be well again....

A complete example is given below:

using System;

using System.Collections.Generic;

using System.IO;

using System.Text;

using System.Xml;

using System.Xml.XPath;

using System.Xml.Xsl;

using System.Xml.Schema;

....

public static string TransformXml(string xml, string xsl)

{

/* Load the xml into an XmlReader*/

XmlReader rXml = CreateXmlReaderFromString(xml);

/* Load the xsl into an XmlReader*/

XmlReader rXsl = CreateXmlReaderFromString(xsl);

Stream oStream = new MemoryStream();

using (TextWriter tr = new StreamWriter(oStream, outputEncoding))

{

/* Create a XslCompiledTransform class to do the transformation */

XslCompiledTransform trans = new XslCompiledTransform();

trans.Load(rXsl);

trans.Transform(rXml, null, tr);

// declare a buffer to hold the contents of the stream

byte[] arrBuffer = new byte[oStream.Length];

// we have to set the position to 0 so that it moves the pointer back to

// the start of where we want to read

oStream.Position = 0;

// read from the stream to our buffer

int iLastLength = oStream.Read(arrBuffer, 0, (int)oStream.Length);

// have we read anything

if (iLastLength > 0)

{

// get our transformed xml using our encoder and the buffer

xml = outputEncoding.GetString(arrBuffer);

}

else

{

xml = string.Empty;

}

}

return xml;

}

private static XmlTextReader CreateXmlReaderFromString(string XML)

{

XmlTextReader xmlReader = null;

StringReader sReader = new StringReader(XML);

xmlReader = new XmlTextReader(sReader);

return xmlReader;

}

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Posted On Monday, November 27, 2006 2:38 PM | Feedback (2) | Filed Under [ .Net Oddities Articles ]

Powered by: