TechyMedia

A .NET Technology blog | .NET,C# Progamming,C# tutorials,WPF WCF|Software Engineer

NAVIGATION - SEARCH

XPATH With Default Namespace In C# - XpathNavigator

This article explains the sample C# code using XPath Navigator to select an XML element from an XML file which is having a default namespace.Normal xpath expression won't return anything if there is a namespace defined in Xml file.

This article explains the sample C# code with XPathNavigator to select an XML element from an XML file which is having a default namespace.

Consider the sample XML file with namespace(xmlns) defined ,

<?xml version="1.0" encoding="UTF-8"?>
<Country xmlns="http://www.countrys.org/2013/13/CountrySchema" version="1.2">
  <State Name="Maharashtra">   
    <City>Mumbai</City>
    <City>Pune</City> 
  </State>
  <State Name="Karnataka">
    <City>Bangalore</City>
    <City>Mangalore</City>
  </State>
</Country>

See the console application sample given below which selects all the City Elements of the State which is having Name attribute value 'Karnataka'.XPathNavigator is used for parsing.

class Program
{
       static void Main(string[] args)
       {      

            //Replace the hard coded xml  file path wth your xml file path.
            XPathDocument xpathDocument = new XPathDocument(@"E:\XmlSamples\Country.xml");
            XPathNavigator navigator = xpathDocument.CreateNavigator();

            //Define the Namespace manager
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable());
            nsmgr.AddNamespace("ns", "http://www.countrys.org/2013/13/CountrySchema");
       
            //Set the Xpath expression
            string xPathQuery = "//ns:State[@Name='Karnataka']/ns:City";
            XPathNodeIterator nodes = navigator.Select(xPathQuery, nsmgr);
            foreach (XPathNavigator item in nodes)
            {             
               Console.WriteLine(item.InnerXML);
            }
            Console.Read();
    }
}

Since the XML is having a namespace defined in it, your Xpath expression need name space manager which is defined with the 2 lines below.This namespace manager is used in XpathNavigator select.

XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable());
nsmgr.AddNamespace("ns", "http://www.countrys.org/2013/13/CountrySchema");

Notice the Xpath expression  //ns:State[@Name='Karnataka']/ns:City , here the text ns:(instead of ns,use any variable name as you like) before every element name is needed since the XML file is having a default namespace.Every node name in the expression need this namespace text.

Comments (1) -

Margarett Provance
United States Margarett Provance

Awesome site, great info.

Reply

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading