将Linq保存为Xml文件作为ANSI而不是C#中的UTF-8(Ivy) [英] Saving a Linq to Xml file as ANSI instead of UTF-8 in C# (Ivy)
问题描述
在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.
我目前有一个大障碍,那就是使用.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> barṸbaz</foo>" );
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = new ASCIIEncoding();
using (var writer = XmlWriter.Create( "xelement.xml", settings )) {
doc.Save( writer );
}
这篇关于将Linq保存为Xml文件作为ANSI而不是C#中的UTF-8(Ivy)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!