C# - XML / XPath problem

kag

Golden Member
May 21, 2001
1,677
0
76
www.boloxe.com
I have the following code and I cannot figure why xnList is always an empty list. I'm not sure if "xml" doesn't contain what I think it does, of if my XPath expression is wrong.

This is the XML file I'm fetching:
http://picasaweb.google.com/data/feed/api/user/ghebert?kind=album

Code:
string url = "http://picasaweb.google.com/data/feed/api/user/" + username.Text + "?kind=album";

WebRequest request = WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();

response.Close();
dataStream.Close();
reader.Close();

XmlDocument xml = new XmlDocument();
xml.LoadXml(responseFromServer);

XmlNodeList xnList = xml.SelectNodes("/feed/entry");
MessageBox.Show("Found: " + Convert.ToString( xnList.Count ));
 

Oyster

Member
Nov 20, 2008
151
0
0
I don't have access to the IDE, so can't really debug this. But from the looks of it, the <entry> node is under the default namespace - xmlns='http://www.w3.org/2005/Atom'. Your XPath expression, it seems, is failing because it can't locate an <entry> node without a namespace resolution.

Look into the XmlNameSpaceManager on MSDN. I am pretty certain that adding the namespace to the manager and then using the current XPath expression will be successful. Here is an example: http://msdn.microsoft.com/en-us/library/d271ytdx.aspx
 

kag

Golden Member
May 21, 2001
1,677
0
76
www.boloxe.com
Thanks, that fixed my problem, I'm not sure I understand the whole XML namespace thing though. I added these two lines and ajusted my XPath expression.

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

XmlNodeList xnList = xml.SelectNodes("/fd:feed/fd:entry", nsmgr);
 
Last edited:

Oyster

Member
Nov 20, 2008
151
0
0
Well, namespaces play a pretty important role - especially when you're dealing with Web Services, RSS feeds, etc. The XmlNamespaceManager allows you to pool all the namespaces you may encounter in an XML document. Beyond that, selecting nodes based on namespaces is more of a W3C standard than a .NET-specific thing.

Look up XLinq and Xml to LINQ - working with namespaces is pretty trivial at this point. Nonetheless, you'll want to know what they are and why they're used.

Forgot to include the tutorial on namespaces: http://www.w3schools.com/xml/xml_namespaces.asp
 
Last edited: