如何在转换之前将xsl:param添加/插入到xsl样式表中?

时间:2011-03-30 12:16:52

标签: javascript dom xslt

给出以下代码(并且不使用jQuery) 在转换之前将标签动态插入xsl的好方法是什么?我希望有人“修复”函数addParam

function addParam(xsl,name,value) {

/** input:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">    
  <xsl:template match="/">.....

output:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">    
  <xsl:param name="parm1" value="parameter number 1" />      
  <xsl:template match="/">.....
*/

   var parameter = document.createElement("xsl:param");
   parameter.setAttribute("name",name);
   parameter.setAttribute("value",value);
   xsl.documentElement.insertBefore(parameter,xsl.documentElement.firstsChild)

}

function displayResult(pXml) {  
    var xsl = loadXMLDoc("cdcatalog.xsl");
    // code for IE
    if (window.ActiveXObject) {

    /* I want to call it here >>> */ 
        addParam(xsl,"parm1","parameter value1");

        var ex = pXml.transformNode(xsl);
        document.getElementById("availableSearchItems").innerHTML = ex;
    }
    // code for Mozilla, Firefox, Opera, Chrome, etc.
    else if (document.implementation && document.implementation.createDocument) {
        xsltProcessor = new XSLTProcessor();
        xsltProcessor.importStylesheet(xsl);

    /* I want to call it here */ 
        addParam(xsl,"parm1","parameter value1");

        resultDocument = xsltProcessor.transformToFragment(pXml, document);
        document.getElementById('availableSearchItems').innerHTML = "";
        document.getElementById("availableSearchItems").appendChild(resultDocument);
    }
}

我已阅读how to pass a parameter from an URL to a XSL stylesheet using jQuery?并了解Firefox可以执行setParameter而IE可以执行

var strParam = "//xsl:param[@name='" + p + "']";
var xslParam = xObj.selectSingleNode(strParam);                     
xslParam.setAttribute("select",op[p]);

但是假设xsl已经有一个参数。

指针和更正非常受欢迎。 感谢

1 个答案:

答案 0 :(得分:1)

为什么要更改xsl中的参数名称?当然,这可能是静态的,你改变了该参数的值是什么?然后,您可以在JavaScript中设置要传递给xsl的内容,并以此方式执行,并且很容易。

<xsl:param name="parm1"/>

然后,当您调用add和set参数函数时,它会获得一个值,如下所示。您甚至可以测试以确保它在传递之前不为空。

//code for ie
if (window.ActiveXObject)
{   
    var xslt = new ActiveXObject("MSXML2.FreeThreadedDOMDocument");
    xslt.async = false;
    xslt.load(xsl);
    var template = new ActiveXObject("MSXML2.XSLTemplate");
    template.stylesheet = xslt;
    var process = template.createProcessor();
    process.input = xml;
    if(yourparam != ""){
        process.addParameter("paramID", yourparam);
    }
    process.transform();
}
// code for Mozilla, Firefox, Opera, etc.
else if (document.implementation && document.implementation.createDocument)
{
    var xml_serializer = new XMLSerializer();
    xsltProcessor=new XSLTProcessor();
    xsltProcessor.importStylesheet(xsl);
    if(yourparam != ""){
        xsltProcessor.setParameter(null, "paramID", yourparam);   
    }
}