asp.net簡單生成XML文件的方法

字號:


    本文實例講述了asp.net簡單生成XML文件的方法。分享給大家供大家參考,具體如下:
    方式一:直接使用DataSet
    SqlConnection conn = new SqlConnection();
    conn.ConnectionString = "Server=127.0.0.1;User ID=sa;Password=sa;Database=northwind;Persist Security Info=True";
    conn.Open();
    SqlDataAdapter da = new SqlDataAdapter("select * from 表", conn);
    SqlCommandBuilder thisBulder = new SqlCommandBuilder(da);
    DataSet ds = new DataSet();
    da.Fill(ds);
    ds.WriteXml(@"C:/temp.xml");
    方式二:自定義生成方式
    using System.Xml;//頭部加此命名空間
    XmlDocument xd = new XmlDocument();//表示XML文檔
    XmlDeclaration xde;//表示 XML 聲明節(jié)點:<?xml version='1.0'...?>
    xde = xd.CreateXmlDeclaration("1.0", "GBK", null);//參數(shù)的第二項為編碼方式
    //standalone定義了是否可以在不讀取任何其它文件的情況下處理該文檔,默認為no
    xd.AppendChild(xde);//<?xml version="1.0" encoding="UTF-8" standalone="yes"?>生成結(jié)束
    XmlElement xe = xd.CreateElement("Root");//創(chuàng)建一個Root根元素
    xd.AppendChild(xe);//Root根元素創(chuàng)建完成
    XmlNode root = xd.SelectSingleNode("Root");//查找<Root>
    XmlElement xe1 = xd.CreateElement("Tree");//在<Root>之下創(chuàng)建元素<Tree>
    xe1.SetAttribute("id","1");//指定屬性的屬性值
    xe1.InnerText = "類型1";//指定屬性文本節(jié)點
    root.AppendChild(xe1);//完成子節(jié)點<Tree>
    xd.Save(Server.MapPath("xml.xml"));
    希望本文所述對大家asp.net程序設計有所幫助。