将 HTTP 响应正文解析为 XML [英] Parse HTTP response body to XML

查看:40
本文介绍了将 HTTP 响应正文解析为 XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此代码执行 HTTP 请求并解析 XML 响应:

I'm using this code to perform an HTTP request and parse the XML response:

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 如下所示:

<?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>

生成的类如下所示:

[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; }
}

我想做的是这样的:

if(Obj_response.Status.code == 200)
{
    // something to happen on successful request
}
else
{
    // write the response text to log
}

推荐答案

最终我发现了问题,问题出在这一行 t = ms.ReadToEnd();导致流通过末端导致没有任何东西.

eventually i found the problem, the problem was with this line t = ms.ReadToEnd(); that cause the stream to lap through the end cause nothing to be after that.

这篇关于将 HTTP 响应正文解析为 XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆