我的代码尝试从网站的RSS Feed中获取数据。它可以很好地抓取节点,但是当尝试从带有冒号的节点中获取数据时,它会崩溃并提供错误“需要命名空间管理器或XsltContext。此查询具有前缀,变量或用户定义的函数。”代码如下所示:
WebRequest request = WebRequest.Create("http://buypoe.com/external.php?type=RSS2&lastpost=true");
WebResponse response = request.GetResponse();
StringBuilder sb = new StringBuilder("");
System.IO.StreamReader rssStream = new System.IO.StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding("utf-8"));
XmlDocument rssDoc = new XmlDocument();
rssDoc.Load(rssStream);
XmlNodeList rssItems = rssDoc.SelectNodes("rss/channel/item");
for (int i = 0; i < 5; i++)
{
XmlNode rssDetail;
rssDetail = rssItems.Item(i).SelectSingleNode("dc:creator");
if (rssDetail != null)
{
user = rssDetail.InnerText;
}
else
{
user = "";
}
}
我知道我需要定义命名空间,但我不确定如何执行此操作。帮助将不胜感激。
答案 0 :(得分:19)
您必须先使用XmlNamespaceManager声明dc
命名空间前缀,然后才能在XPath表达式中使用它:
XmlDocument rssDoc = new XmlDocument();
rssDoc.Load(rssStream);
XmlNamespaceManager nsmgr = new XmlNamespaceManager(rssDoc.NameTable);
nsmgr.AddNamespace("dc", "http://purl.org/dc/elements/1.1/");
XmlNodeList rssItems = rssDoc.SelectNodes("rss/channel/item");
for (int i = 0; i < 5; i++) {
XmlNode rssDetail = rssItems[i].SelectSingleNode("dc:creator", nsmgr);
if (rssDetail != null) {
user = rssDetail.InnerText;
} else {
user = "";
}
}