使用浏览器转换XML时是否可以通过URL向XSLT传递参数?
题
当使用浏览器(Google Chrome 或 IE7)转换 XML 时,是否可以通过 URL 将参数传递给 XSLT 样式表?
例子:
数据.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>
样本.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 动态读取它们。然而,这些不能在 XSLT(XPath 表达式)中使用 - 因为浏览器已经转换了 XML/XSLT。它们只能在渲染的 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";
}
}
不隶属于 StackOverflow