今天做一个项目,需要把数据输出成XML。
开始是用DataSet.GetXml()来输出XML,不过数据库中的数据有一个字段是XML类型的,而用DataSet.GetXmL()的话,那个XML类型的字段里的值不会被当成XML来输出,而是当作值来输出的。
所以后来就用了SQL 的FOR XML来把所有的数据以XML格式从数据读取。
- public XmlDocument Getxml()
- {
- SqlConnection sqlConnection = new SqlConnection("Server=localhost;Initial Catalog=Canyin;User ID=sa;Password=sa");
- SqlCommand mycmd = new SqlCommand("select * from table for xml auto,elements,root", sqlConnection);
- XmlDocument xmldom = new XmlDocument();
- XmlReader xr;
- try
- {
- sqlConnection.Open();
- xr = mycmd.ExecuteXmlReader();
- while(xr.Read())
- {
- xmldom.Load(xr);
- }
- }
- catch
- {
- throw;
- }
- finally
- {
- sqlConnection.Close();
- }
- return xmldom;
- }