Reputation: 7253
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
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:
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>
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;
}
eventName
text is Special Name
as expected.Upvotes: 1
Reputation: 1950
This should work:
XmlNode nameOfEvent = doc.SelectSingleNode("/Event/Event_Name");
string text = nameOfEvent.InnerText;
eventName.Text = text;
Upvotes: 0