Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPathSelectElement always returns null

Tags:

c#

xml

xpath

Why is this Xpath not working using XDocument.XPathSelectElement?

Xpath:

//Plugin/UI[1]/PluginPageCategory[1]/Page[1]/Group[1]/CommandRef[2] 

XML

<Plugin xmlns="http://www.MyNamespace.ca/MyPath">   <UI>     <PluginPageCategory>       <Page>         <Group>           <CommandRef>             <Images>             </Images>           </CommandRef>           <CommandRef>             <Images>             </Images>           </CommandRef>         </Group>       </Page>     </PluginPageCategory>   </UI> </Plugin> 

C# Code:

myXDocument.XPathSelectElement("//Plugin/UI[1]/PluginPageCategory[1]/Page[1]/Group[1]/CommandRef[2]", myXDocument.Root.CreateNavigator()); 
like image 722
Jean-Philippe Leclerc Avatar asked Apr 28 '11 13:04

Jean-Philippe Leclerc


1 Answers

When namespaces are used, these must be used in the XPath query also. Your XPath query would only work against elements with no namespace (as can be verified by removing the namespace from your XML).

Here's an example showing how you create and pass a namespace manager:

var xml = ... XML from your post ...;  var xmlReader = XmlReader.Create( new StringReader(xml) ); // Or whatever your source is, of course. var myXDocument = XDocument.Load( xmlReader ); var namespaceManager = new XmlNamespaceManager( xmlReader.NameTable ); // We now have a namespace manager that knows of the namespaces used in your document. namespaceManager.AddNamespace( "prefix", "http://www.MyNamespace.ca/MyPath" ); // We add an explicit prefix mapping for our query.  var result = myXDocument.XPathSelectElement(     "//prefix:Plugin/prefix:UI[1]/prefix:PluginPageCategory[1]/prefix:Page[1]/prefix:Group[1]/prefix:CommandRef[2]",     namespaceManager ); // We use that prefix against the elements in the query.  Console.WriteLine(result); // <CommandRef ...> element is printed. 

Hope this helps.

like image 147
Cumbayah Avatar answered Oct 03 '22 02:10

Cumbayah