[英]Parse HTTP response body to XML
I'm using this code to perform an HTTP request and parse the XML response:我正在使用此代码执行 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;
}
}
It shows:表明:
Root element is missing.
缺少根元素。
The XML looks like this: XML 如下所示:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE cXML SYSTEM "http://xml.cXML.org/schemas/cXML/1.1.009/cXML.dtd">
<cXML payloadID="Web" xml:lang="en-US" timestamp="3/7/2016 5:21:43 AM">
<Response>
<Status code="200" text="OK" />
<JobID>WebOrder 69</JobID>
</Response>
</cXML>
And the generated classes look like this:生成的类如下所示:
[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 = "http://www.w3.org/XML/1998/namespace")]
public string Lang { get; set; }
[XmlAttribute(AttributeName = "timestamp")]
public string Timestamp { get; set; }
}
What I want to do is something like that:我想做的是这样的:
if(Obj_response.Status.code == 200)
{
// something to happen on successful request
}
else
{
// write the response text to log
}
eventually i found the problem, the problem was with this line t = ms.ReadToEnd();
最终我发现了问题,问题出在这一行
t = ms.ReadToEnd();
that cause the stream to lap through the end cause nothing to be after that.这导致流通过末端导致没有之后。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.