Using XPath with XML returned by SharePoint Web services

Using XPath with XML returned by SharePoint Web services

I’ve seen quite often people writing code that parses thru XML returned by SPS Web services as strings instead of using XPath – cause the XmlDocument throws this error all the time if you dont use an XmlNameSpaceManager

“Namespace Manager or XsltContext needed. This query has a prefix, variable, or user-defined function.”

Heres a snippet that tells you how to use the XmlNameSpaceManager to use XPath with the XmlDocument.

Dim Document As New XmlDocument
Dim xml As String

xml = “”

‘Since the XML returned by SPS contains namespace prefixes – we need to create a XmlNamespaceManager
Dim SharePointNamespacePrefix As String = “sp”
Dim SharePointNamespaceURI As String = “”

Dim ListItemsNamespacePrefix As String = “z”
Dim ListItemsNamespaceURI As String = “#RowsetSchema”

Dim PictureLibrariesNamespacePrefix As String = “s”
Dim PictureLibrariesNamespaceURI As String = “uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882”

Dim WebPartsNamespacePrefix As String = “dt”
Dim WebPartsNamespaceURI As String = “uuid:C2F41010-65B3-11d1-A29F-00AA00C14882”

Dim DirectoryNamespacePrefix As String = “rs”
Dim DirectoryNamespaceURI As String = “urn:schemas-microsoft-com:rowset”

‘now associate with the xmlns namespaces (part of all XML nodes returned
‘from SharePoint) a namespace prefix which we can then use in the queries
Dim NamespaceMngr As XmlNamespaceManager
NamespaceMngr = New XmlNamespaceManager(Document.NameTable)

NamespaceMngr.AddNamespace(SharePointNamespacePrefix, SharePointNamespaceURI)
NamespaceMngr.AddNamespace(ListItemsNamespacePrefix, ListItemsNamespaceURI)
NamespaceMngr.AddNamespace(PictureLibrariesNamespacePrefix, PictureLibrariesNamespaceURI)
NamespaceMngr.AddNamespace(WebPartsNamespacePrefix, WebPartsNamespaceURI)
NamespaceMngr.AddNamespace(DirectoryNamespacePrefix, DirectoryNamespaceURI)

‘run the XPath query and return the result nodes
Dim xNodeList As XmlNodeList
xNodeList = Document.SelectNodes(“//z:row[@ows_Title]”, NamespaceMngr)