Friday, July 2, 2010

How To Handdle XSL output HTML charset

Some times we transfrom xsl to html will get a wrong html chartset.
In C# we usually using TextWriter or XmlTextWriter to output a stream from xsl transformation, but the default encoding of the TextWriter and XmlTextWriter have a potential pitfall makes you difficult to fine out the real reason cause the wrong html charset automatically reander by xsl transform.
By defaul TextWriter and XmlTextWriter using UTF-16 encoding, it cause XSL Trasformation automatically generate html charset to UTF-16, What if you already defined html chartset in your xsl you will find out there a duplicated content-type defined in your output html head like this:
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-16" />
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        .....
        .....
Solution:
      
      no more best guidance than a real sample code....
XmlDocument xDoc = new XmlDocument();
xDoc.Load(new Uri(Request.Url, xmlUrl).ToString());
XslCompiledTransform xTrans = new XslCompiledTransform();
xTrans.Load(new Uri(Request.Url, xslUrl).ToString());
StringBuilder sb = new StringBuilder();
XmlWriterSettings xmlWriterSettings = new XmlWriterSettings()
{
    Encoding = Encoding.UTF8
    ,
    // if you don't want any xml declaration output such as <?xml ... ?>
    OmitXmlDeclaration = true    
};
          XmlWriter xWriter = XmlTextWriter.Create(sb, xmlWriterSettings);
          xTrans.Transform(xDoc, null, xWriter);
        
         // get result there
        System.Console.Write(sb.ToString());
       
        xWriter.Close();
        // if you want directly write to response
        XmlTextWriter xTxtWriter = new XmlTextWriter(Response.OutputStream, Encoding.UTF8);
        xTxtWriter.Close();

No comments: