还可以向XSLT中传入参数或对象,先看如何向其传入参数,比如要改变上例的背景颜色,则可以这样写XSLT
| <?xml version="1.0" ?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="html" /> <xsl:param name="BackGroundColor" select="Blue" /> <xsl:template match="/"> <HTML> <HEAD> <TITLE>Passing Parameters to an XSLT Style Sheet</TITLE> </HEAD> <BODY> <H2> Passing Parameters to an XSLT Style Sheet</H2> <table border="1" cellSpacing="1" cellPadding="1"> <center> <xsl:for-each select="//Categories"> <!-- Each record on a seperate row --> <xsl:element name="tr"> <xsl:attribute name="bgcolor"> <xsl:value-of select="$BackGroundColor" /> </xsl:attribute> <xsl:element name="td"> <xsl:value-of select="ProductSubcategoryID" /> </xsl:element> <xsl:element name="td"> <xsl:value-of select="Name" /> </xsl:element> <xsl:element name="td"> <xsl:attribute name="align">center</xsl:attribute> <xsl:value-of select="ModifiedDate" /> </xsl:element> </xsl:element> </xsl:for-each> </center> </table> </BODY> </HTML> </xsl:template> </xsl:stylesheet> |
要注意的是其中的是:
| <xsl:attribute name="bgcolor"> <xsl:value-of select="$BackGroundColor" /> |
以这样的形式指定了backgroundcolor是一个参数,而在XSLT的一开始,以<xsl:param name="BackGroundColor" select="Blue" />的方式,为backgroundcolor设定了一个值为蓝色,这样则为使<tr>的背景颜色bgcolor=blue,实现将输出数据的每一行变为蓝色的效果。
当然,在上面的例子中,我们是已硬编码的方式设置xslt的参数,一般来说,应该在asp.net 页面中进行设置。而在asp.net 2.0中,可以使用XsltArgumentList类来向XSLT中传递参数,具体使用方法如下:
| <%@ Page Language="C#" %> <%@ Import Namespace="System.Data.SqlClient" %> <%@ Import Namespace="System.Xml" %> <%@ Import Namespace="System.Xml.Xsl" %> <%@ Import Namespace="System.Xml.XPath" %> <%@ Import Namespace="System.Web.Configuration" %> <script runat="server"> void Page_Load(object sender, System.EventArgs e) { string connString = WebConfigurationManager.ConnectionStrings ["adventureWorks"].ConnectionString; using (SqlConnection connection = new SqlConnection(connString)) { connection.Open(); SqlCommand command = new SqlCommand ("Select * from Production.ProductSubCategory as Categories " + " for xml auto,elements", connection); XmlReader reader = command.ExecuteXmlReader(); XPathDocument xpathDoc = new XPathDocument(reader); string xslPath = Server.MapPath("App_Data/Category.xsl"); XslCompiledTransform transform = new XslCompiledTransform(); transform.Load(xslPath); XsltArgumentList argsList = new XsltArgumentList(); string backGroundColor = "Tan"; //Add the required parameters to the XsltArgumentList object argsList.AddParam("BackGroundColor", "", backGroundColor); transform.Transform(xpathDoc, argsList, Response.Output); } } |
其中,注意黑体加粗部分,先实例化了XsltArgumentList类,接着设置了backGroundColor颜色,再使用XsltArgumentList类的addParam方法,向XSLT中原先设置好的BackGroundColor传递参数。最后,在XslCompiledTransform的transform方法中,其中的第二个参数,传入刚才实例化后的argsList,这样就可以实现在aspx页面中动态向XSLT中传递进参数了,实现的效果如下图所示
- 相关新闻
- 用户评论
数据载入中,请稍后……
评论内容:不能超过100字,不需审核,请自觉遵守互联网相关政策法规。
- 推广服务
IT部落推荐阅读
·生活服务
·精彩图文
·赞助商链接
Rss订阅


