HttpWebResponse.GetResponseStream转换<代替<etc

时间:2019-03-28 12:32:46

标签: c# asp.net xml asp.net-web-api

HttpWebResponse.GetResponseStream转换<而不是<等。 我正在使用HttpWebRequest从Web服务检索XML数据。 Web API

我的内容类型是: request.ContentType =“ application / json”;

问题是,当我检索文本时,信封,响应之内的所有内容都会被转换。所以<>是<和>等等。

如何检索数据,并为有效XML保留小于/大于符号?

谢谢!

replace方法在xml <>包络之间转换所有我不想要的特殊字符

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "application/json";
//request.ContentType = "text/xml;charset=utf-8";

request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
request.Method = HttpVerb;
request.Accept = "application/xml";
if (ObjData != null)
{
    var Serialized = JsonConvert.SerializeObject(ObjData);
    using (StreamWriter sw = new StreamWriter(request.GetRequestStream()))
    {
        sw.Write(Serialized);
    }
}
else
{
    request.ContentLength = 0;
}
HttpWebResponse httpWebResponse = request.GetResponse() as HttpWebResponse;

using (StreamReader sr = new StreamReader(httpWebResponse.GetResponseStream()))
{
    if (httpWebResponse.StatusCode == HttpStatusCode.Unauthorized || httpWebResponse.StatusCode == HttpStatusCode.InternalServerError || httpWebResponse.StatusCode == HttpStatusCode.NotAcceptable)
    {
        strResponse = httpWebResponse.StatusDescription;
    }
    else if (httpWebResponse.StatusCode != HttpStatusCode.OK)
    {
        strResponse = String.Format("POST failed. Received HTTP {0}", httpWebResponse.StatusCode);
    }
    else
    {
        strResponse = sr.ReadToEnd();// this line creating the wrong xml
        strResponse = XMLDecode(strResponse);
    }
}

1 个答案:

答案 0 :(得分:1)

这3行代码解决了我的问题:

strResponse = sr.ReadToEnd(); //这在转换<图表时用&lt等

会产生问题。

XmlDocument xmlDocument = new XmlDocument(); //这三行代码解决了xml问题

xmlDocument.LoadXml(strResponse);

strResponse = xmlDocument.InnerText;