Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

c# - set response encoding from XML

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...