在 C# (Ivy) 中将 Linq 保存为 ANSI 而不是 UTF-8 [英] Saving a Linq to Xml file as ANSI instead of UTF-8 in C# (Ivy)

查看:27
本文介绍了在 C# (Ivy) 中将 Linq 保存为 ANSI 而不是 UTF-8的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C# 中,我需要创建用于 Ivy 和 NAnt 的 XML 文件,但我很难在输出文件中获得正确的编码.

In C#, I need to create XML files for use with Ivy and NAnt, but am having difficulty in getting the right encoding in the output file.

如果我使用 XElement 的 .Save("C:foo.xml"),我会得到正确的外观文件,但 Ivy 和/或 NAnt 会感到不安,因为文件实际上是使用UTF-8 但我实际上需要将它保存为 ANSI 才能使用它.

If I use XElement's .Save("C:foo.xml"), I get the correct looking file, but Ivy and/or NAnt gets upset, as the file is actually saved using UTF-8 but I actually need to save it as ANSI in order to be able to use it.

我目前有一个bodge,即使用.ToString() 获取文本,然后使用StreamWriter 将其写入文件.

I have a bodge in place at present, which is to use .ToString() to get the text and then use a StreamWriter to write it to a file.

理想情况下,我想在 .Save() 期间设置格式,但找不到任何相关信息.

Ideally, I'd like to set the format during the .Save() but can't find any information on this.

谢谢.

推荐答案

XDocument.Save 有许多重载.

通过正确构造的 XmlWriter 写入允许我们选择 ASCII 编码.

Writing via a properly constructed XmlWriter allows us to choose the ASCII encoding.

var doc = XDocument.Parse( "<foo>&#160;bar&#7800;baz</foo>" );

XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = new ASCIIEncoding();
using (var writer = XmlWriter.Create( "xelement.xml", settings )) {
    doc.Save( writer );
}

这篇关于在 C# (Ivy) 中将 Linq 保存为 ANSI 而不是 UTF-8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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