将HTTP响应主体解析为XML
我正在使用此代码执行HTTP请求并解析XML响应:
using (HttpWebResponse resp = req.GetResponse() as HttpWebResponse) { if (resp.StatusCode == HttpStatusCode.OK) { var Obj_response = new CXML(); var ms = new StreamReader(resp.GetResponseStream(), UTF8Encoding.UTF8); t = ms.ReadToEnd();// <---- This line Caused the issue XmlSerializer serializer = new XmlSerializer(typeof(CXML)); Obj_response = (CXML)serializer.Deserialize(ms);// <------ NOT WORKING return true; } }
表明:
根元素缺失。
XML看起来像这样:
WebOrder 69
生成的类看起来像这样:
[XmlRoot(ElementName = "Status")] public class Status { [XmlAttribute(AttributeName = "code")] public string Code { get; set; } [XmlAttribute(AttributeName = "text")] public string Text { get; set; } } [XmlRoot(ElementName = "Response")] public class Response { [XmlElement(ElementName = "Status")] public Status Status { get; set; } [XmlElement(ElementName = "JobID")] public string JobID { get; set; } } [XmlRoot(ElementName = "cXML")] public class CXML { [XmlElement(ElementName = "Response")] public Response Response { get; set; } [XmlAttribute(AttributeName = "payloadID")] public string PayloadID { get; set; } [XmlAttribute(AttributeName = "lang", Namespace = "https://www.w3.org/XML/1998/namespace")] public string Lang { get; set; } [XmlAttribute(AttributeName = "timestamp")] public string Timestamp { get; set; } }
我想做的是这样的:
if(Obj_response.Status.code == 200) { // something to happen on successful request } else { // write the response text to log }
最终我发现了问题,问题出在这条线上t = ms.ReadToEnd();
导致流经过末端的原因导致了之后没有任何事情发生。
上述就是C#学习教程:将HTTP响应主体解析为XML分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1003562.html