当使用浏览器转换XML时,是否可以通过URL传递参数到XSLT?

16
当使用浏览器(例如Google Chrome或IE7)转换XML时,是否可以通过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>
3个回答

8

很遗憾,您不能仅在客户端传递参数到XSLT。Web浏览器从XML中获取处理指令,并直接使用XSLT进行转换。


可以通过查询字符串URL传递值,然后使用JavaScript动态读取这些值。但是,这些值无法在XSLT(XPath表达式)中使用 - 因为浏览器已经转换了XML / XSLT。它们只能用于呈现的HTML输出。


6

只需将参数作为属性添加到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";
   }
}

4

即使转换是客户端的,您也可以在服务器端生成XSLT。这使您可以使用动态脚本来处理参数。

例如,您可能会指定:

<?xml-stylesheet type="text/xsl"href="/myscript.cfm/sample.xsl?paramter=something" ?>

然后在myscript.cfm中,您将输出XSL文件,但使用动态脚本处理查询字符串参数(这取决于您使用的脚本语言)。


6
问题的第二部分是:它是否仅能在客户端完成? - user9547

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接