在 C# 中将 Xml UTF-8 转换为 ISO-8859-9

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/964649/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 04:22:15  来源:igfitidea点击:

Converting Xml UTF-8 to ISO-8859-9 in c#

c#xmlutf-8

提问by enormous81

i have a long xml document just created by string builder with the starting tag like <?xml version="1.0" encoding="UTF-8"?> <xxxxxx> .. </xxxxxx> and i want to convert this xml to iso-8859-9 encoding type. How can i do this? Or anyone suggests me another way to create ISO-8859-9 encoding type xml in C#.

我有一个刚由字符串生成器创建的长 xml 文档,其起始标记为 like <?xml version="1.0" encoding="UTF-8"?> <xxxxxx> .. </xxxxxx> ,我想将此 xml 转换为 iso-8859-9 编码类型。我怎样才能做到这一点?或者有人建议我在 C# 中创建 ISO-8859-9 编码类型 xml 的另一种方法。

回答by Jon Skeet

I'd suggest that the most robust way would be to load it as an XML document, and then save it with a TextWriterwhich has an encoding of ISO-8859-9. That way you don't need to worry about anything XML-specific.

我建议最可靠的方法是将其作为 XML 文档加载,然后TextWriter使用编码为 ISO-8859-9 的a 保存它。这样您就无需担心任何特定于 XML 的问题。

How do you want the output? In a string, a file, a byte array?

你想要怎样的输出?在字符串、文件、字节数组中?

回答by Tor Haugen

Since encoding only makes sense when text is encoded into a stream, I assume you want to save the document to a file using the given encoding. That way, the encoding attribute will match the file's encoding.

由于编码仅在将文本编码到流中时才有意义,因此我假设您想使用给定的编码将文档保存到文件中。这样,编码属性将匹配文件的编码。

Try:

尝试:

using System.IO;
using System.Xml;

XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
Stream stream = File.Open(path, FileMode.Create, FileAccess.Write, FileShare.None);
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.GetEncoding("ISO-8859-9");
XmlWriter writer = XmlWriter.Create(stream, settings);
doc.Save(writer);

回答by enormous81

thank you for your answer it is really helpfull for me. Besides that i noticed that the sample code below.

谢谢你的回答,这对我真的很有帮助。除此之外,我注意到下面的示例代码。

string xml ="our created xml string";

HttpResponse Response = context.Response;
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/xls";
Response.Charset = "UTF-8";
Response.ContentEncoding = Encoding.GetEncoding("UTF-8");
Response.AddHeader("content-disposition", "attachment; filename=text.xml" ) ;
Response.Output.Write(xml);

if i just change the Charset property of Response and ContentEncoding Property of Response, Can i reach the your solution? ? will only change these two lines:

如果我只是更改 Response 的 Charset 属性和 Response 的 ContentEncoding 属性,我能找到您的解决方案吗?? 只会改变这两行:

Response.Charset = "ISO-8859-9";                                        
Response.ContentEncoding = Encoding.GetEncoding("ISO-8859-9");

does it works?

它有效吗?