我希望在输出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"><hello</text>
必需的输出
<?xml version="1.0" encoding="utf-16"?><text xmlns="temp-uri"><!CDATA[<hello]]></text>
我在这里缺少什么?
答案 0 :(得分:4)
您的XmlWriter必须被告知当前的输出设置:
XmlWriter results = XmlWriter.Create(new StringWriter(sb), t.OutputSettings);
//---------------------------------------------------------^^^^^^^^^^^^^^^^