使用浏览器转换XML时,是否可以通过URL将参数传递给XSLT?
时间:2020-03-05 18:54:17 来源:igfitidea点击:
使用浏览器转换XML(Google Chrome或者IE7)时,是否可以通过URL将参数传递给XSLT样式表?
例子:
data.xml
<?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type="text/xsl" href="sample.xsl"?> <root> <document type="resume"> <author>John Doe</author> </document> <document type="novella"> <author>Jane Doe</author> </document> </root>
sample.xsl
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format"> <xsl:output method="html" /> <xsl:template match="/"> <xsl:param name="doctype" /> <html> <head> <title>List of <xsl:value-of select="$doctype" /></title> </head> <body> <xsl:for-each select="//document[@type = $doctype]"> <p><xsl:value-of select="author" /></p> </xsl:for-each> </body> </html> </<xsl:stylesheet>
解决方案
回答
即使转换是在客户端,我们也可以生成XSLT服务器端。
这使我们可以使用动态脚本来处理参数。
例如,我们可以指定:
<?xml-stylesheet type="text/xsl"href="/myscript.cfm/sample.xsl?paramter=something" ?>
然后,在myscript.cfm中,我们将输出XSL文件,但使用动态脚本来处理查询字符串参数(这取决于所使用的脚本语言)。
回答
不幸的是,没有,我们不能仅在客户端将参数传递给XSLT。
Web浏览器从XML中获取处理指令。并直接使用XSLT对其进行转换。
可以通过查询字符串URL传递值,然后使用JavaScript动态读取它们。但是,由于浏览器已经转换了XML / XSLT,因此无法在XSLT(XPath表达式)中使用它们。它们只能在呈现的HTML输出中使用。
回答
只需将参数作为属性添加到XML源文件中,并将其用作样式表的外观即可。
xmlDoc.documentElement.setAttribute("myparam",getParameter("myparam"))
JavaScript函数如下:
//Get querystring request paramter in javascript function getParameter (parameterName ) { var queryString = window.top.location.search.substring(1); // Add "=" to the parameter name (i.e. parameterName=value) var parameterName = parameterName + "="; if ( queryString.length > 0 ) { // Find the beginning of the string begin = queryString.indexOf ( parameterName ); // If the parameter name is not found, skip it, otherwise return the value if ( begin != -1 ) { // Add the length (integer) to the beginning begin += parameterName.length; // Multiple parameters are separated by the "&" sign end = queryString.indexOf ( "&" , begin ); if ( end == -1 ) { end = queryString.length } // Return the string return unescape ( queryString.substring ( begin, end ) ); } // Return "null" if no parameter has been found return "null"; } }