Saving a Linq to Xml file as ANSI instead of UTF-8 in C# (Ivy)

半城伤御伤魂 提交于 2019-12-01 04:20:21

问题


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.

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.

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.

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

Thanks.


回答1:


XDocument.Save has a number of overloads.

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


来源:https://stackoverflow.com/questions/2253021/saving-a-linq-to-xml-file-as-ansi-instead-of-utf-8-in-c-sharp-ivy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!