XSLT / XML / C# (转)
这个例程展示了如何将xslt 应用于从数据库中读出的XML格式数据上. 例程完全使用C#语言编写:
using System;
using System.Collections;
using System.Data;
using System.Data.SqlClient;
using System.XML;
using System.XML.Xsl;
public class XsltTransform
{
public static void Transform()
{
SqlConnection nwindConn = new SqlConnection("Data
Source=INMUMIS123;database=northwind;uid=sa;pwd=;");
nwindConn.Open();
DataSet custDS = new DataSet("CustomerDataSet");
SqlDataAdapter custDA = new SqlDataAdapter("SELECT * FROM Customers",
nwindConn);
custDA.Fill(custDS, "Customers");
SqlDataAdapter ordersDA = new SqlDataAdapter("SELECT * FROM Orders",
nwindConn);
ordersDA.Fill(custDS, "Orders");
nwindConn.Close();
custDS.Relations.Add("CustOrders",
custDS.Tables["Customers"].Columns["CustomerID"],
custDS.Tables["Orders"].Columns["CustomerID"]).Nested = true;
XMLDataDocument XMLDoc = new XMLDataDocument(custDS);
XslTransform xslTran = new XslTransform();
xslTran.Load("transform.xsl");
// This is for generating the output in new HTML
XMLTextWriter writer = new XMLTextWriter("xslt_output.HTML",
System.Text.Encoding.UTF8);
writer.Close();
// This is for writing in the current page
xslTran.Transform(XMLDoc, null, Response.OutputStream);
}
}
上面这个称为XsltTransform的类连接到一个数据库,将数据填充到XMLDocument 中,然后将下面提供的Xslt应用于这个XML.
<%@ Page language="c#"%>
public void Page_Load(object sender, System.EventArgs e)
{
Transform();
}
public void Transform()
{
SqlConnection nwindConn = new SqlConnection("Data
Source=INMUMIS123;database=northwind;uid=sa;pwd=;");
nwindConn.Open();
DataSet custDS = new DataSet("CustomerDataSet");
SqlDataAdapter custDA = new SqlDataAdapter("SELECT * FROM Customers",
nwindConn);
custDA.Fill(custDS, "Customers");
SqlDataAdapter ordersDA = new SqlDataAdapter("SELECT * FROM Orders",
nwindConn);
ordersDA.Fill(custDS, "Orders");
nwindConn.Close();
custDS.Relations.Add("CustOrders",
custDS.Tables["Customers"].Columns["CustomerID"],
custDS.Tables["Orders"].Columns["CustomerID"]).Nested = true;
XMLDataDocument XMLDoc = new XMLDataDocument(custDS);
XslTransform xslTran = new XslTransform();
xslTran.Load("transform.xsl");
// XMLTextWriter writer = new XMLTextWriter("xslt_output.HTML",
System.Text.Encoding.UTF8);
xslTran.Transform(XMLDoc, null, Response.OutputStream);
// writer.Close();
}
上面的ASPx page 用这个类(XsltTranform)建立了一对象, 然后调用了Transform 函数
。
BODY {font-family:verdana;font-size:9pt}
TD {font-size:8pt}
| Order: | |
| Date: | |
| Ship To: |
最后是这个xslt 文件

