Search code examples
c#xmlxpathnamespacesxpathnavigator

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?


Solution

  • 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);