onTheInternet
onTheInternet

Reputation: 7253

Value of xml node returning as null

I have an xml document that I am loading in my asp .net application. It is structured like this

-<Event>

    <Event_Name>Special Name</Event_Name>
    <Event_Date>5/27/2016 12:00:00 AM</Event_Date>
    <Event_Description>Event Description</Event_Description>

</Event>

I am loading it in my code behind like this

    XmlDocument doc = new XmlDocument();
    string path = Server.MapPath("~/NewsXMLNews.xml");
    doc.Load(path);

This loads properly. The problem is, I want to set the Event_Name as the text of a label on my aspx page. I do this using the following code

   string nameOfEvent = doc.SelectSingleNode("Event_Name").ToString();
   eventName.Text = nameOfEvent;

The problem is that nameOfEvent is coming back as null, so I get a nullReferenceException

I'm not exactly what I'm doing incorrectly here.

Upvotes: 1

Views: 711

Answers (2)

Tommaso Cerutti
Tommaso Cerutti

Reputation: 495

Since you already checked the path is correct and the document is properly loaded I think you just need to change the following line:

    string nameOfEvent = doc.SelectSingleNode("/Event/Event_Name").InnerText;

Edit: I check with following steps that xml loading process works:

  1. I remove the minus before in described xml file and saved following lines as c:\temp\Event.xml:

    <?xml version="1.0" encoding="UTF-8"?> 
    <Event> 
       <Event_Name>Special Name</Event_Name> 
       <Event_Date>5/27/2016 12:00:00 AM</Event_Date> 
       <Event_Description>Event Description</Event_Description> 
    </Event>
    
  2. Then I succeeded in running:

       public Form1()
       {
           InitializeComponent();            
           XmlDocument doc = new XmlDocument(); 
           string path = "c:\\temp\\Event.xml"; 
           doc.Load(path); 
           string nameOfEvent = doc.SelectSingleNode("/Event/Event_Name").InnerText; 
           eventName.Text = nameOfEvent;
       }
    
  3. In my window I see Label named eventName text is Special Name as expected.

Upvotes: 1

Mike Debela
Mike Debela

Reputation: 1950

This should work:

XmlNode nameOfEvent = doc.SelectSingleNode("/Event/Event_Name");
string text = nameOfEvent.InnerText;
eventName.Text = text;

Upvotes: 0

Related Questions