Thanks to the help I receive earlier, I'm making some progress with my code to generate an xml file based on records found in my database, but I'm stuck again:
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 41: root.AppendChild(mainNode);
here's my new code:
Code:
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDb" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Xml" %>
<script runat="server">
protected void Page_Load (object sender, EventArgs e) {
XmlDocument xmlDoc = new XmlDocument();
XmlNode xn=xmlDoc.CreateElement("event");
xmlDoc.AppendChild(xn);
using (SqlConnection conn = new SqlConnection(@"Data Source=mssql;Initial Catalog=xxxxx;User Id=xxxxx;Password=xxxxx;"))
{
conn.Open();
SqlCommand cmd = new SqlCommand("select NewsNo, NewsEventDate, EventStartTime, EventEndTime, NewsHeadline, NewsDetails, NewsCategory from DailyNews where NewsCategory = 'event'", conn);
XmlNode root= xmlDoc.SelectSingleNode("/events");
SqlDataReader sdr = cmd.ExecuteReader();
if (sdr.HasRows)
{
while (sdr.Read())
{
XmlElement mainNode = xmlDoc.CreateElement("event");
XmlElement idNode= xmlDoc.CreateElement("NewsNo");
XmlElement eventDateNode= xmlDoc.CreateElement("NewsEventDate");
XmlElement startTimeNode= xmlDoc.CreateElement("EventStartTime");
XmlElement endTimeNode= xmlDoc.CreateElement("EventEndTime");
XmlElement eventNameNode= xmlDoc.CreateElement("NewsHeadline");
XmlElement eventDetailsNode= xmlDoc.CreateElement("NewsDetails");
idNode.InnerText = sdr.GetInt32(0).ToString();
eventDateNode.InnerText = sdr.GetDateTime(1).ToString();
startTimeNode.InnerText = sdr.GetString(2);
endTimeNode.InnerText = sdr.GetString(3);
eventNameNode.InnerText = sdr.GetString(4);
eventDetailsNode.InnerText = sdr.GetString(5);
mainNode.AppendChild(idNode);
mainNode.AppendChild(eventDateNode);
mainNode.AppendChild(startTimeNode);
mainNode.AppendChild(endTimeNode);
mainNode.AppendChild(eventNameNode);
mainNode.AppendChild(eventDetailsNode);
root.AppendChild(mainNode);
}
}
xmlDoc.Save("events.xml");
}
}
Thanks in advance!