如何使用 XSLT 和 XMLWRITER 创建具有特定编码的 XML [英] How to create a XML with a Specific Encoding using XSLT and XMLWRITER

查看:27
本文介绍了如何使用 XSLT 和 XMLWRITER 创建具有特定编码的 XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在源 xml 上应用 XSL 样式表并将输出写入目标 xml 文件.xsl 删除源 xml 中存在的 xml 注释.

I am trying to apply a XSL style sheet on a source xml and write the output to a target xml file. The xsl removes the xml comments present inside the source xml.

目标 xml 文件在标头中具有 UTF-16 编码.

The target xml file has UTF-16 encoding in the header.

但我仍然希望输出 xml 是 utf-8 编码.我使用的代码是

But still i want the output xml to be utf-8 encoding. The code i used is

            XmlWriterSettings xwrSettings = new XmlWriterSettings();
            **xwrSettings.Encoding = Encoding.UTF8;**

            XslCompiledTransform xslt = new XslCompiledTransform();
            xslt.Load("sample.xsl");
            StringBuilder sb = new StringBuilder();
            XmlReader xReader = XmlReader.Create("Source.xml");
            XmlWriter xWriter = XmlWriter.Create(sb, xwrSettings);                
            xslt.Transform(xReader, xWriter);
            File.WriteAllText("Target.xml",sb.ToString());

我尝试将 xml writer 设置设为 UTF-8,但它不起作用.

I tried to set the xml writer setting to be of UTF-8 but it is not working.

推荐答案

既然要写入文件,何不直接使用:

Since you are writing to file, why not just use:

using (XmlReader xReader = XmlReader.Create("Source.xml"))
using (XmlWriter xWriter = XmlWriter.Create("Target.xml", xwrSettings)) {
    xslt.Transform(xReader, xWriter);
}
// your file is now written

这篇关于如何使用 XSLT 和 XMLWRITER 创建具有特定编码的 XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆