<script type="text/javascript"> </script> <script class="blogstory"> </script>
创建过程:创建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>
- <strong><font color="#ff0000" >ReaderXml.aspx.cs代码如下:</font></strong><pre class = "csharp" name= "code" > 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" ;
- ///创建Command
- SqlCommand 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>" );
- ///关闭XMLReader
- myxmlReader.Close();
- }
- catch (SqlException sqlex)
- {
- ///显示链接错误的消息
- Response.Write(sqlex.Message + "<br>" );
- }
- finally
- {
- ///关闭数据库的链接
- myConnection.Close();
- }
- Response.End();
- }
- }
- </pre>