第一种方式,直接使用DataSet:
![ContractedBlock.gif](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![ExpandedBlockStart.gif](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
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 " );
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 " );
第二种方式,自定义XML,使用XmlDocument:
![ContractedBlock.gif](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![ExpandedBlockStart.gif](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
using
System.Xml;
//
头部加此命名空间
XmlDocument xd = new XmlDocument(); // 表示XML文档
XmlDeclaration xde; // 表示 XML 声明节点:<?xml version='1.0'...?>
xde = xd.CreateXmlDeclaration( " 1.0 " , " GBK " , null ); // 参数的第二项为编码方式
// standalone定义了是否可以在不读取任何其它文件的情况下处理该文档,默认为no
xd.AppendChild(xde); // <?xml version="1.0" encoding="UTF-8" standalone="yes"?>生成结束
XmlElement xe = xd.CreateElement( " Root " ); // 创建一个Root根元素
xd.AppendChild(xe); // Root根元素创建完成
XmlNode root = xd.SelectSingleNode( " Root " ); // 查找<Root>
XmlElement xe1 = xd.CreateElement( " Tree " ); // 在<Root>之下创建元素<Tree>
xe1.SetAttribute( " id " , " 1 " ); // 指定属性的属性值
xe1.InnerText = " 类型1 " ; // 指定属性文本节点
root.AppendChild(xe1); // 完成子节点<Tree>
xd.Save(Server.MapPath( " xml.xml " ));
XmlDocument xd = new XmlDocument(); // 表示XML文档
XmlDeclaration xde; // 表示 XML 声明节点:<?xml version='1.0'...?>
xde = xd.CreateXmlDeclaration( " 1.0 " , " GBK " , null ); // 参数的第二项为编码方式
// standalone定义了是否可以在不读取任何其它文件的情况下处理该文档,默认为no
xd.AppendChild(xde); // <?xml version="1.0" encoding="UTF-8" standalone="yes"?>生成结束
XmlElement xe = xd.CreateElement( " Root " ); // 创建一个Root根元素
xd.AppendChild(xe); // Root根元素创建完成
XmlNode root = xd.SelectSingleNode( " Root " ); // 查找<Root>
XmlElement xe1 = xd.CreateElement( " Tree " ); // 在<Root>之下创建元素<Tree>
xe1.SetAttribute( " id " , " 1 " ); // 指定属性的属性值
xe1.InnerText = " 类型1 " ; // 指定属性文本节点
root.AppendChild(xe1); // 完成子节点<Tree>
xd.Save(Server.MapPath( " xml.xml " ));