How to Select XML Nodes with XML Namespaces from an XmlDocument?

爷,独闯天下 提交于 2020-03-07 06:11:32

问题


my code attempts to grab data from the RSS feed of a website. It grabs the nodes fine, but when attempting to grab the data from a node with a colon, it crashes and gives the error "Namespace Manager or XsltContext needed. This query has a prefix, variable, or user-defined function." The code is shown below:

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 = "";
   }
}

I understand that I need to define the namespace, but am unsure how to do this. Help would be appreciated.


回答1:


You have to declare the dc namespace prefix using an XmlNamespaceManager before you can use it in XPath expressions:

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 = "";
    }
}


来源:https://stackoverflow.com/questions/4633127/how-to-select-xml-nodes-with-xml-namespaces-from-an-xmldocument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!