Question

I have a application where i read the xml information. It is working fine, but when my parent node has an XMLNS added into it, it stops working and starts throwing Null reference exception.

What should be the possible solution for this

XML File

<Info  xmlns="urn:smilu.com">
  <Number>123456</Number>  
  <Gender>2</Gender>
  <NamesEng>
    <First>FirstName</First>
    <Second>SecondName</Second>
    <Third>ThirdName</Third>
    <Fourth>FourthName</Fourth>
    <Fifth>FifthName</Fifth>
    <Sixth>SixthName</Sixth>
  </NamesEng> 
</Info>

My C# code for reading is

 NameTable nt = new NameTable();
XmlNamespaceManager nsMgr = new XmlNamespaceManager(nt);                
nsMgr.AddNamespace("ns", "urn:smilu.com");

XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(_LabourXMLInfo);

string Number = xdoc.DocumentElement.SelectSingleNode("Number", nsMgr).InnerText;

The above code works perfectly if i remove the xmlns from the Info node. But, with xmlns added to it, shows me exception. Kindly help me on this.

Was it helpful?

Solution

You're declaring the XML namespace - but you're not actually using it (referring to it).

Change your code to:

XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(_LabourXMLInfo);

// define XML namespace manager based on the XmlDocument's NameTable
XmlNamespaceManager nsMgr = new XmlNamespaceManager(xdoc.NameTable);
nsMgr.AddNamespace("ns", "urn:smilu.com");

// add a "ns:" prefix to the XPath expression here!
string Number = xdoc.DocumentElement.SelectSingleNode("ns:Number", nsMgr).InnerText;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top