.NET XslTransform mystery - META charset in transformation output
I have following piece of code:
using (Stream stream = new MemoryStream())
{
xslt.Transform(document, xslArg, stream);
stream.Seek(0, SeekOrigin.Begin);
StreamReader reader = new StreamReader(stream);
var result = reader.ReadToEnd();
return resu开发者_运维百科lt;
}
That transformation outputs HTML document. What is bewildering to me is that even though the input xsl contains:
<html>
<head>
<style>
@page Section1
{size:612.0pt 792.0pt;
margin:42.55pt 42.55pt 42.55pt 70.9pt;
mso-header-margin:35.45pt;
mso-footer-margin:35.45pt;
mso-paper-source:0;}
div.Section1
{page:Section1;}
</head>
<body>
<div class="Section1">
.....
output is :
<html xmlns:ms="urn:schemas-microsoft-com:xslt" xmlns:dt="urn:schemas-microsoft-com:datatypes">
<head>
<META http-equiv="Content-Type" content="text/html; charset=utf-8">
<style>.....
as you see, charset info was added, apart from other stuff.
But what really amazed me, was that when I changed code that makes transformation into:
StringBuilder sb = new StringBuilder();
using (StringWriter writer = new StringWriter(sb))
{
xslt.Transform(document, xslArg, writer);
}
var result = sb.ToString();
return result;
generated output had the following form:
<html xmlns:ms="urn:schemas-microsoft-com:xslt" xmlns:dt="urn:schemas-microsoft-com:datatypes">
<head>
<META http-equiv="Content-Type" content="text/html; charset=utf-16">
<style>....
As you can see, charset has changed. I guess it's because StringBuilder, and .NET by default operates using UTF-16. But, why transformation appends META tag with charset anyway?
Well either your stylesheet has <xsl:output method="html"/>
or the root element of the result tree has the local name html
and is in no namespace. In both cases the XSLT specification mandates that the XSLT processors adds a meta element with content type and charset in the head section when serializing the result tree.
精彩评论