从数据库中读取XML数据

来源:互联网 发布:咏春交易软件 编辑:程序博客网 时间:2024/05/09 18:53

创建过程:创建SQL语句打开数据库连接,并调用ExecuteXmlReader()方法从数据库中读取数据,并返回一个XmlReader对象myxmlReader,然后用While语句循环读取XmlReader对象myxmlReader中的XML片段,并添加XML文件的起始、结尾标志,构建一个XML文件,最后把该文件输出到页面ReaderXml.aspx上面。

ReaderXml.aspx代码如下:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="ReaderXml.aspx.cs" Inherits="_Default" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server">    <title>从数据库中读取XML数据</title></head><body>    <form id="form1" runat="server">    <div>        </div>    </form></body></html>ReaderXml.aspx.cs代码如下:
using System;using System.Data;using System.Configuration;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;using System.Data.SqlClient;using System.Xml;public partial class _Default : System.Web.UI.Page {    protected void Page_Load(object sender, EventArgs e)    {if(!Page.IsPostBack){   ///从数据库读取XML数据ReaderXmlData();}    }private void ReaderXmlData(){///创建链接SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLCONNECTIONSTRING"].ConnectionString);///定义SQL语句string cmdText = "SELECT * FROM Users FOR XML AUTO";///创建CommandSqlCommand myCommand = new SqlCommand(cmdText,myConnection);try{///打开连接myConnection.Open();XmlReader myxmlReader = myCommand.ExecuteXmlReader();///移动到XML元素处myxmlReader.MoveToElement();///输出XML文件的标志Response.Write("<?xml version='1.0'?>");///输出父节点Response.Write("<Users>");///读取从数据库中获取的数据while(myxmlReader.IsStartElement()){///显示从数据库中获取的数据Response.Write(myxmlReader.ReadOuterXml());}Response.Write("</Users>");///关闭XMLReadermyxmlReader.Close();}catch(SqlException sqlex){///显示链接错误的消息Response.Write(sqlex.Message + "<br>");}finally{///关闭数据库的链接myConnection.Close();}Response.End();}}