Stuck Streaming Xml

时间:2012-08-23 10:42:43

标签: asp.net xml

这是我为了获取一个网址的xml而编写的代码,但它说 “根级别的数据无效”,任何网址都可以。有人可以说明原因吗?

XmlDocument xdoc = new XmlDocument();//xml doc used for xml parsing                           
xdoc.LoadXml("http://latestpackagingnews.blogspot.com/feeds/posts/default");//loading XML in xml doc
XmlNodeList xNodelst = xdoc.DocumentElement.SelectNodes("entry");//reading node so that we can traverse thorugh the XML
Response.Write(xNodelst);

3 个答案:

答案 0 :(得分:0)

XmlDocument.LoadXml方法等待XML文本,但不是源URL。

首先,将页面内容下载到string,然后将其传递给LoadXml。您可以在此下载:

public string GetUrlContent(string url)
{
    var request = (HttpWebRequest)HttpWebRequest.Create(url);
    var response = (HttpWebResponse)request.GetResponse();

    var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
    var content = reader.ReadToEnd();

    reader.Close();
    response.Close();

    return content;
}

在你的情况下,它将是:

var content = GetUrlContent("http://latestpackagingnews.blogspot.com/feeds/posts/default");
var doc = new XmlDocument();
doc.LoadXml(content);

答案 1 :(得分:0)

xdoc.LoadXml无法读取网址,将其更改为xdoc.Load即可。

您还可以阅读:Using Returned XML with C#

答案 2 :(得分:0)

您需要先使用WebClient类

下载xml数据
string downloadedString;
System.Net.WebClient client = new System.Net.WebClient();
downloadedString = client.DownloadString("http://latestpackagingnews.blogspot.com/feeds/posts/default");
//Now write this string as an xml
//I think you can easily do it with XmlDocument class and then read it