.NET XPath Returns No Results
Posted
by Stacy Vicknair
on Geeks with Blogs
See other posts from Geeks with Blogs
or by Stacy Vicknair
Published on Thu, 10 Mar 2011 20:57:00 GMT
Indexed on
2011/03/11
0:11 UTC
Read the original article
Hit count: 224
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);
© Geeks with Blogs or respective owner