2

这是我为获取一个 url 的 xml 而编写的代码,但它对任何 url 都显示“根级别的数据无效”。有人可以指定原因吗?

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);
4

3 回答 3

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);
于 2012-08-23T10:50:04.143 回答
0

xdoc.LoadXmlcan not for read url,将其更改为,xdoc.Load它将起作用。

您还可以阅读:将返回的 XML 与 C# 结合使用

于 2012-08-23T10:50:06.157 回答
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
于 2012-08-23T10:54:37.287 回答