資料庫和XML __ 從資料庫中提取xml

sage425發表於2010-11-26

 

從資料庫中提取xml

別忘了 引用

using System.Xml;

using System.Xml.XPath;

using System.Data.SqlClient;

-------------------------------------

 

protected void Page_Load(object sender, EventArgs e)

{

DataBaseXMl();

}

 

 

 

  /// <summary>

    /// 從資料庫中提取xml

    /// </summary>

    public void DataBaseXMl()

    {

        string DB_conStrings = ConfigurationManager.ConnectionStrings["DB_study"].ConnectionString;

        XmlDocument x = new XmlDocument();

        XPathNavigator xpathnav = x.CreateNavigator();

        using (SqlConnection conn = new SqlConnection(DB_conStrings))

        {

            conn.Open();

            SqlCommand command = new SqlCommand("select * from book as book for xml auto,elements",conn);

            using (XmlWriter xw = xpathnav.PrependChild())

            {

                xw.WriteStartElement("books");

                using (XmlReader reader = command.ExecuteXmlReader())

                {

                    xw.WriteNode(reader, true);

                }

                xw.WriteEndElement();

            }

        }

        //Response.ContentType = "text/xml";

        //x.Save(Response.OutputStream);

        Xml1.XPathNavigator = xpathnav;

    }

--------------頁面-----------------------------------------------

<asp:Xml ID="Xml1" runat="server" TransformSource="~/book.xsl"></asp:Xml>

----------------------------book.xsl---------------------------------------------

 

<?xml version="1.0" encoding="utf-8"?>

<xsl:stylesheet version="1.0"

    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">

    <html>

    <body>

<h3>list of book</h3>

<table border="1">

<tr>

<th>編號</th>

<th>作者</th>

<th>名字</th>

</tr>

<xsl:apply-templates select="//book"/>

</table>

    </body>

    </html>

</xsl:template>

<xsl:template match="book">

<tr>

<td>

<xsl:value-of  select="book_Id"/> </td>

<td>

<xsl:value-of select="book_Author"/>  </td>

<td>

<xsl:value-of select="book_Name"/> </td>

</tr>

</xsl:template>

</xsl:stylesheet> 

 

 

 

 

相關文章