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.)
tagged: professional // Comments [1]
Related posts:Select a random row in MS SQL...Regular expressionsVS2005, ASP.NET 2 & DLLs, DLLs..MS's ASP.NET and.. PHP2-way databinding cascading drop down lists within a FormViewApplicationName Property when customising providers
Disclaimer The posts on this blog are provided "AS IS" with no warranties. The opinions expressed herein are my own personal opinions and do not represent any other person's views in anyway.