学习如何把数据库数据提取为XML
代码:
news.mdb数据库结构:News(id,title,content,time)
string fileurl = System.Web.HttpContext.Current.Server.MapPath("App_Data") + "\\" + "news.mdb";
OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0;Data Source=" +fileurl);
OleDbDataAdapter oda = new OleDbDataAdapter("Select *FROM News",con);
DataSet ds = new DataSet();
oda.Fill(ds,"News");
DataTable dt=ds.Tables["News"];
XmlDocument xdoc = new XmlDocument();
//创建XML申明
XmlDeclaration xdecl = xdoc.CreateXmlDeclaration("1.0", "gb2312", "yes");
xdoc.AppendChild(xdecl);
//创建根元素
XmlElement x_emt = xdoc.CreateElement("news");
xdoc.AppendChild(x_emt);
//从数据库读取数据加到XML中
for (int i = 0; i < dt.Rows.Count;i++)
{
XmlElement xmnew = xdoc.CreateElement("new");
XmlElement xemt = xdoc.CreateElement("ID");
xemt.InnerText = dt.Rows[i]["id"].ToString();
xmnew.AppendChild(xemt);
XmlElement xemt1 = xdoc.CreateElement("TITLE");
xemt1.InnerText = dt.Rows[i]["title"].ToString();
xmnew.AppendChild(xemt1);
XmlElement xemt2 = xdoc.CreateElement("CONTENT");
xemt2.InnerText = dt.Rows[i]["content"].ToString();
xmnew.AppendChild(xemt2);
XmlElement xemt3 = xdoc.CreateElement("TIME");
xemt3.InnerText = dt.Rows[i]["time"].ToString();
xmnew.AppendChild(xemt3);
xdoc.DocumentElement.AppendChild(xmnew);
}
//输出保存
xdoc.Save(@"E:\我的站点\admin\News.xml");
总结:添加XML节点时一定要把子节点添加到对应的父结点下,根节点只能有一个。