Using Xpath With Default Namespace in C#
I've got an XML document with a default namespace. I'm using a XPathNavigator to select a set of nodes using Xpath as follows:
XmlElement myXML = ...;
XPathNavigator navigator = myXML.CreateNavigator();
XPathNodeIterator result = navigator.Select("/outerelement/innerelement");
I am not getting any results back: I'm assuming this is because I am not specifying the namespace. How can I include the namespace in my select?
First - you don't need a navigator; SelectNodes / SelectSingleNode should suffice.
You may, however, need a namespace-manager - for example:
XmlElement el = ...; //TODO
XmlNamespaceManager nsmgr = new XmlNamespaceManager(
el.OwnerDocument.NameTable);
nsmgr.AddNamespace("x", el.OwnerDocument.DocumentElement.NamespaceURI);
var nodes = el.SelectNodes(@"/x:outerelement/x:innerelement", nsmgr);
You might want to try an XPath Visualizer tool to help you through.
XPathVisualizer is free, easy to use.
IMPORTANT: If you are using Windows 7/8 and don't see File, Edit and Help Menu items, please press ALT key.
For anyone looking for a quick hack solution, especially in those cases where you know the XML and don't need to worry about namespaces and all that, you can get around this annoying little "feature" by simply reading the file to a string and replacing the offensive attribute:
XmlDocument doc = new XmlDocument();
string fileData = File.ReadAllText(fileName);
fileData = fileData.Replace(" xmlns=\"", " whocares=\"");
using (StringReader sr = new StringReader(fileData))
{
doc.Load(sr);
}
XmlNodeList nodeList = doc.SelectNodes("project/property");
I find this easier than all the other non-sense requiring a prefix for a default namespace when I'm dealing with a single file. Hope this helps.
When using XPath in .NET (via a navigator or SelectNodes/SelectSingleNode) on XML with namespaces you need to:
provide your own XmlNamespaceManager
and explicitly prefix all elements in XPath expression, which are in namespace.
The latter is (paraphrased from MS source linked below): because XPath 1.0 ignores default namespace specifications (xmlns="some_namespace"). So when you use element name without prefix it assumes null namespace.
That's why .NET implementation of XPath ignores namespace with prefix String.Empty in XmlNamespaceManager and allways uses null namespace.
See XmlNamespaceManager and UndefinedXsltContext don't handle default namespace for more information.
I find this "feature" very inconvenient because you cannot make old XPath namespace-aware by simply adding default namespace declaration, but that's how it works.
You can use XPath statement without using XmlNamespaceManager like this:
...
navigator.Select("//*[ local-name() = 'innerelement' and namespace-uri() = '' ]")
...
That is a simple way of selecting element within XML with default namespace definied.
The point is to use:
namespace-uri() = ''
which will found element with default namespace without using prefixes.