Why does this XPath query not return any nodes?

I request the server side of Sharepoint and return the results as Xml. I want to reduce the Xml to something easier before posting it to jQuery via WebMethod.

However, my XPath request does not work. I thought that the following code will return all Document nodes, but returns nothing. I used to use XPath, I thought that //Document does the trick.

C # XPath Request

 XmlDocument xmlResults = new XmlDocument(); xmlResults.LoadXml(xml); // XML is a string containing the XML source shown below XmlNodeList results = xmlResults.SelectNodes("//Document"); 

XML requested

 <ResponsePacket xmlns="urn:Microsoft.Search.Response"> <Response domain="QDomain"> <Range> <StartAt>1</StartAt> <Count>2</Count> <TotalAvailable>2</TotalAvailable> <Results> <Document relevance="126" xmlns="urn:Microsoft.Search.Response.Document"> <Title>Example 1.doc</Title> <Action> <LinkUrl size="32256" fileExt="doc">http://hqiis99/Mercury/Mercury documents/Example 1.doc</LinkUrl> </Action> <Description /> <Date>2010-08-19T14:44:56+01:00</Date> </Document> <Document relevance="31" xmlns="urn:Microsoft.Search.Response.Document"> <Title>Mercury documents</Title> <Action> <LinkUrl size="0" fileExt="aspx">http://hqiis99/mercury/Mercury documents/Forms/AllItems.aspx</LinkUrl> </Action> <Description /> <Date>2010-08-19T14:49:39+01:00</Date> </Document> </Results> </Range> <Status>SUCCESS</Status> </Response> </ResponsePacket> 
+6
c # xml xpath
source share
2 answers

You are trying to select Document elements that do not have a namespace ... whereas the default namespace is actually "urn: Microsoft.Search.Response" here.

I think you need something like this:

 XmlDocument xmlResults = new XmlDocument(); xmlResults.LoadXml(xml); XmlNamespaceManager manager = new XmlNamespaceManager(xmlResults.NameTable); manager.AddNamespace("ns", "urn:Microsoft.Search.Response.Document"); XmlNodeList results = xmlResults.SelectNodes("//ns:Document", manager); 

This finds two elements.


If you can use LINQ to XML, this will simplify:

 XDocument results = XDocument.Parse(xml); XNamespace ns = "urn:Microsoft.Search.Response.Document"; var documents = results.Descendants(ns + "Document"); 

I like LINQ to XML namespace handling :)

+11
source share

Alternatively, you can try the following and ignore namespaces:

 XmlDocument xmlResults = new XmlDocument(); xmlResults.LoadXml(xmlString); XmlNodeList results = xmlResults.SelectNodes("//*[local-name()='Document']"); 
+3
source share

All Articles