Geeks With Blogs

News INETA Community Speakers Program
GeeksWithBlogs.net: WTFNext's hosting!

View Stacy Vicknair's profile on LinkedIn


WTF Next? Dev ramblings from a master of nothing.

When using XPath in .NET one of the gotchas to be aware of is that all namespaces must be named, otherwise you’ll end up with no results. Default namespaces that are specified with xmlns alone still need to be recognized in the XPath query!

Say I had a bit of XML like what is returned from the QueryService web service in Sharepoint:

   1: <?xml version="1.0" encoding="UTF-8"?>
   2: <ResponsePacket xmlns="urn:Microsoft.Search.Response">
   3:   <Response>
   4:     <Range>
   5:       ...
   6:       <Results>
   7:         <Document xmlns="urn:Microsoft.Search.Response.Document" relevance="849">
   8:             ...

 

When consuming and navigating this response with XPath it is necessary to name all namespaces. Then those named namespaces must be used in reference to the individual element being requested (i.e. doc:Document).

In VB:

   1: Dim xdoc = new XPathDocument(reader)
   2: Dim nav = xdoc.CreateNavigator()
   3: Dim nsMgr = new XmlNamespaceManager(nav.NameTable)
   4: nsMgr.AddNamespace("resp", "urn:Microsoft.Search.Response")
   5: nsMgr.AddNamespace("doc", "urn:Microsoft.Search.Response.Document")
   6:  
   7: Dim results = nav.Select("//doc:Document", nsMgr)

 

In C#:

   1: var xdoc = new XPathDocument(reader);
   2: var nav = xdoc.CreateNavigator();
   3: var nsMgr = new XmlNamespaceManager(nav.NameTable);
   4:  
   5: nsMgr.AddNamespace("resp", "urn:Microsoft.Search.Response");
   6: nsMgr.AddNamespace("doc", "urn:Microsoft.Search.Response.Document");
   7:  
   8: var results = nav.Select("//doc:Document", nsMgr);
Posted on Thursday, March 10, 2011 2:57 PM VB .NET , C# .NET , .NET Tips | Back to top


Comments on this post: .NET XPath Returns No Results

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Stacy Vicknair | Powered by: GeeksWithBlogs.net