set response encoding from XML

2019-09-21 14:07发布

I'm working with XML. I'm received an XML like this:

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

on xxx value is "não ok",but how I convert from "N?o ok" to "Não ok"?

I know that the codification is utf8(1252) but how set this in output xml?

I tryed setting in request:

client.Encoding = Encoding.UTF8;

but does not works. Thanks in advance!

1条回答
霸刀☆藐视天下
2楼-- · 2019-09-21 14:58

Try setting the encoding to the encoding from the code page 1252. The example below uses a simple service to serve the file, and setting the encoding to UTF-8 shows the same problem you have; setting it to the correct encoding works.

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();
    }
}
查看更多
登录 后发表回答