将XslCompiledTransform与cdata-section-elements一起使用

时间:2009-05-15 15:08:00

标签: c# xml xslt

我希望在输出XML中有CDATA部分。我试图使用xsl:output的“cdata-sections-element”属性。但是,我的输出中没有CDATA。

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"">
<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();
        }
    }
}

实际输出

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

必需的输出

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

我在这里缺少什么?

1 个答案:

答案 0 :(得分:4)

您的XmlWriter必须被告知当前的输出设置:

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