开发者

Issue selecting nodes in XML document - Returns NULL

I am parsing an XML document to pull out the first occurrence of "content" node and read the inner text for that node.

The XML file coming in can be seen at:

https://www.googleapis.com/shopping/search/v1/public/products?key=AIzaSyAfaLdRHGKa5Rens--Vpw-KftdzWyxe2co&country=GB&q=5055277014187&alt=atom

The code behind that processes the file is:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestToSend);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream());
string responseString = sr.ReadToEnd();

XmlDocument thisXmlDoc = new XmlDocument();
thisXmlDoc.LoadXml(responseString);

//get Companies
XmlNodeList ocNodesCompany = thisXmlDoc.SelectNodes("//feed/entry/content");
foreach (XmlElement element in ocNodesCompany)
{
    description = element.InnerText;
    testOutput = "<b>" + stockRow["stockitem_text"].ToString() + "</b>: " + description + "<br /><br />";
    break;
}

Response.Write(responseString + "<br /><br />" + testOutput);

Unfortunately even tho开发者_运维百科ugh the XML file is coming through correctly, it is not finding any nodes and therefore returning NULL and not entering the 'foreach' loop.

Thanks for any help.


When using XPath queries for elements that are in some namespace, you have to declare and use namespace prefix.

The following code works:

var nsmgr = new XmlNamespaceManager(new NameTable());
nsmgr.AddNamespace("atom", "http://www.w3.org/2005/Atom");

XmlNodeList ocNodesCompany =
    thisXmlDoc.SelectNodes("/atom:feed/atom:entry/atom:content", nsmgr);

Also, when referring to the root node, you should use / instead of //.


You can use thisXmlDoc.GetElementsByTagName("content"); instead of thisXmlDoc.SelectNodes("//feed/entry/content");

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜