【问题标题】:set response encoding from XML从 XML 设置响应编码
【发布时间】:2011-10-26 01:38:22
【问题描述】:

我正在使用 XML。 我收到了这样的 XML:

<ajax-response>
<response>
<item>
<number></number>
<xxx>N?o ok</xxx>
<error>null</error>
</item>
</response>
</ajax-response>

xxx 值为“não ok”,但我如何将“N?o ok”转换为“Não ok”?

我知道编码是 utf8(1252) 但如何在输出 xml 中设置?

我尝试在请求中设置:

client.Encoding = Encoding.UTF8;

但不起作用。 提前致谢!

【问题讨论】:

  • 什么是 utf8(1252) 肯定是 utf8 或 windows 1252 但不是两者都
  • 为什么是-2? @calos:是的,我从远程服务器读取 XML..

标签: c# .net xml encoding utf-8


【解决方案1】:

尝试将编码设置为代码页 1252 中的编码。下面的示例使用一个简单的服务来提供文件,并且将编码设置为 UTF-8 显示了您遇到的相同问题;将其设置为正确的编码即可。

public class StackOverflow_7044842
{
    const string xml = @"<ajax-response>
<response>
<item>
<number></number>
<xxx>Não ok</xxx>
<error>null</error>
</item>
</response>
</ajax-response>";

    [ServiceContract]
    public class SimpleService
    {
        [WebGet]
        public Stream GetXml()
        {
            WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
            Encoding encoding = Encoding.GetEncoding(1252);
            return new MemoryStream(encoding.GetBytes(xml));
        }
    }
    public static void Test()
    {
        string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
        WebServiceHost host = new WebServiceHost(typeof(SimpleService), new Uri(baseAddress));
        host.Open();
        Console.WriteLine("Host opened");

        WebClient client = new WebClient();
        client.Encoding = Encoding.GetEncoding(1252);
        string response = client.DownloadString(baseAddress + "/GetXml");
        Console.WriteLine(response);

        Console.Write("Press ENTER to close the host");
        Console.ReadLine();
        host.Close();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-28
    • 1970-01-01
    • 1970-01-01
    • 2013-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多