• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

C# - XML / XPath problem

kag

Golden Member
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 ));
 
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
 
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:
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:
Back
Top