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/5/Country" version="1.2">
<state name="Maharashtra">
<city>Pune</city>
<city>Mumbai </city>
</state>
<state name="Maharashtra">
<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 hardcoded XML file path with 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 namespace 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 needs this namespace text.
Leave a Reply