使用Xdocument缺少根元素

时间:2014-10-09 20:08:18

标签: c# .net xml httpresponse

使用以下代码我得到"缺少Root元素。"对某些请求发送但使用完全相同的数据标准:

    HttpWebRequest WebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("http://example.com");
    HttpWebResponse WebResponse = null;
    Encoding ResponseEncoding = null;
    StreamReader ResponseReader = null;
    XNamespace ns = "http://example.com/ns";
    XDocument XDoc = null;

    WebRequest.Method = RequestedMethod(ref MethodType);
    WebRequest.ContentType = Contenttype;
    WebRequest.KeepAlive = true;

    try
    {
        WebResponse = (System.Net.HttpWebResponse)WebRequest.GetResponse();
        if (WebResponse != null)
        {
            ResponseEncoding = System.Text.Encoding.UTF8;
            m_ResponseStream = WebResponse.GetResponseStream();
            ResponseReader = new StreamReader(m_ResponseStream, ResponseEncoding);
            XDoc = XDocument.Parse(ResponseReader.ReadToEnd());
        }
    }
    catch (Exception ex)
    {
        //Catch Exception

    }
    finally
    {
        if (ResponseReader != null)
        {
            ResponseReader.Close();
            ResponseReader.Dispose();
        }

        if (WebResponse != null)
        {
            WebResponse.Close();
        }
    }

我已调试此代码,但每次调试时,它总是返回正确的数据。如果我以正常方式运行应用程序,则同样的数据请求会经常显示错误消息。我们的想法是将响应读入XDoc并使用Xdoc迭代节点并执行所需的任何操作。

我已经检查了互联网上的解决方案,但我认为我已经涵盖了我能想到的一切,但我不知道为什么错误会在某些场景中弹出,但从不在调试模式中。有什么想法吗?我已经看到了这个链接,我认为我已经涵盖了必需品"Root element is missing" error but I have a root element

0 个答案:

没有答案