我的代码尝试从网站的RSS提要中获取数据。它可以很好地捕获节点,但是当尝试使用冒号从节点中捕获数据时,它会崩溃并显示错误“需要名称空间管理器或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 = ""; } }
我了解我需要定义名称空间,但是不确定如何执行此操作。帮助将不胜感激。
您必须先dc使用XmlNamespaceManager声明名称空间前缀,然后才能在XPath表达式中使用它:
dc
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 = ""; } }