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());
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With