문제

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.

도움이 되었습니까?

해결책

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;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top