Please add a new XML file. In that add a root element like
<infoRoot>
</infoRoot>
After that Please add this code
Namespaces
using System.Xml;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
C#
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = GetData();
foreach (DataRow row in dt.Rows)
{
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(Server.MapPath(@"XMLFile.xml"));
XmlElement newelement = xmldoc.CreateElement("usercomments");
XmlElement xmlName = xmldoc.CreateElement("name");
XmlElement xmlEmail = xmldoc.CreateElement("email");
XmlElement xmlContent = xmldoc.CreateElement("comments");
xmlName.InnerText = row["Name"].ToString();
xmlEmail.InnerText = row["Email"].ToString();
xmlContent.InnerText = row["CommentBody"].ToString();
newelement.AppendChild(xmlName);
newelement.AppendChild(xmlEmail);
newelement.AppendChild(xmlContent);
xmldoc.DocumentElement.AppendChild(newelement);
xmldoc.Save(Server.MapPath(@"XMLFile.xml"));
}
}
private DataTable GetData()
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Comments", con))
{
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
}
}
}
SQL
CREATE TABLE [dbo].[Comments](
[CommentId] [int] IDENTITY(1,1) NOT NULL,
[CommentBody] [nvarchar](2000) NOT NULL,
[Name] [varchar](30) NOT NULL,
[Email] [nvarchar](50) NOT NULL,
CONSTRAINT [PK_Comments] PRIMARY KEY CLUSTERED
(
[CommentId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO