use*_*547 16 xml browser xslt param transform
使用浏览器转换XML(谷歌浏览器或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>
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
不幸的是,没有 - 你不能仅在客户端将参数传递给XSLT.Web浏览器从XML获取处理指令; 并使用XSLT直接转换它.
可以通过查询字符串URL传递值,然后使用JavaScript动态读取它们.但是这些在XSLT(XPath表达式)中不可用 - 因为浏览器已经转换了XML/XSLT.它们只能用于呈现的HTML输出.
只需将参数作为属性添加到XML源文件中,并将其用作样式表的属性.
xmlDoc.documentElement.setAttribute("myparam",getParameter("myparam"))
Run Code Online (Sandbox Code Playgroud)
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";
}
}
Run Code Online (Sandbox Code Playgroud)
即使转换是在客户端进行的,您也可以在服务器端生成 XSLT。
这允许您使用动态脚本来处理参数。
例如,您可以指定:
<?xml-stylesheet type="text/xsl"href="/myscript.cfm/sample.xsl?paramter=something" ?>
Run Code Online (Sandbox Code Playgroud)
然后在 myscript.cfm 中,您将输出 XSL 文件,但使用动态脚本处理查询字符串参数(这将根据您使用的脚本语言而有所不同)。