Saturday, November 25, 2006

Reading XML output using XMLDocument class and considering namespaces*

Saturday, November 25, 2006 12:00:56 AM (GMT Standard Time, UTC+00:00)

Prerequisite: When reading XML I usually use the XML.XMLDocument class and its SelectNodes() or ChildNodes() methods.

So today whilst using this method to read some XML which was output from a RPC I made, I again used the SelectedNodes method. Sad to say, this time it didn't work. When I tried "SelectedNodes("//result")" (which should return all the 'result' nodes), no nodes were returned even though they were there!

Upon investigation of this problem though (about 2hrs worth of searching I might add :(), I found out that it was because the XML doc that was returned from the RPC had a default namespace included (this doesn't always happen, but mostly occurs from online XML output) i.e. the root node read "<bookstore xmlns="urn:newbooks-schema">".

Now, once a document has this included, one must use the overloaded SelectedNodes() function, which also takes an XMLNamespaceManager object. As MSDN Library states, "If your XML includes a default namespace, you must still add a prefix and namespace URI to the XmlNamespaceManager; otherwise, you does not get any nodes selected." <- i.e., what was happening to me!

So, now the 'fix'... assuming the XML document is a local file with the namespace suggested below.

Dim doc As XmlDocument = New XmlDocument()
doc.Load("newbooks.xml")

' Create an XmlNamespaceManager to resolve the default namespace.
Dim nsmgr As XmlNamespaceManager = New XmlNamespaceManager(doc.NameTable) nsmgr.AddNamespace("bk", "urn:newbooks-schema")

' Select all book titles.
Dim nodeList As XmlNodeList
Dim root As XmlElement = doc.DocumentElement
nodeList = root.SelectNodes("/bk:bookstore/bk:book/bk:title", nsmgr)

(This is an excerpt from the MSDN Library help. The full version, including the XML document can be found here.)

Related posts:
Select a random row in MS SQL...
Regular expressions
VS2005, ASP.NET 2 & DLLs, DLLs..
MS's ASP.NET and.. PHP
2-way databinding cascading drop down lists within a FormView
ApplicationName Property when customising providers

Saturday, November 25, 2006 3:33:26 AM (GMT Standard Time, UTC+00:00)
hmm, this is what i had to do to use regular XmlDocument with YouTube's XML-RPC API instead of having to use the XMLRPC.NET dll..

Nice work.. Took me more than 2 hours to figure out. I had to bruteforce that thing! arghh!!

gonna post the code for that on my website soon
Comments are closed.