Tuesday, November 10, 2009

Write Xml File Via Sql

Comment everything from the aspx page and write below code in the code behind files

1.==================================
string Con = "Data Source="46\\SQLEXPRESS2008;User id=sa;password=murli;Initial Catalog=Murli";
XmlDocument xDoc = new XmlDocument();
XPathNavigator xPath = xDoc.CreateNavigator();
using (SqlConnection Conn = new SqlConnection(Con))
{
Conn.Open();
SqlCommand Cmd = new SqlCommand("Select * from Product As Products For Xml Auto,Elements", Conn);
using (XmlWriter xW = xPath.PrependChild())
{
xW.WriteStartElement("Products");
using (XmlReader xR = Cmd.ExecuteXmlReader())
{
xW.WriteNode(xR, true);
}
xW.WriteEndElement();
}
}
Response.ContentType = "text/xml";
xDoc.Save(Response.Output);

2.=================================
using System.IO;
using System.Text;
using System.Data.SqlClient;


protected void Button1_Click(object sender, EventArgs e)
{
string str = "";
SqlConnection con = new SqlConnection("Data Source=MyDataSource\\SQLEXPRESS2008;Initial Catalog=Murli;User ID=sa;Password=murli");
con.Open();
string s = "select * from tblAnswer";
SqlCommand cmd = new SqlCommand(s, con);
SqlDataReader dr = cmd.ExecuteReader();
StringBuilder sb = new StringBuilder();
sb.Append("");
sb.Append("");
while (dr.Read())
{
sb.Append("");
sb.Append("" + dr[0].ToString() + "");
sb.Append("" + dr[1].ToString() + "");
sb.Append("");
}
sb.Append("");

StreamWriter stw = File.CreateText("D://mutest1.xml");
stw.WriteLine(sb.ToString());
stw.Close();
}

No comments:

Post a Comment