2012-11-11 57 views
2

我一直在寻找其他问题,但我不明白我做错了什么。 我想传递一个参数来选择某些结果,但我遇到了这个参数的问题。XSLT传递参数

在HTML(无视IE部分)

<html> 
<head> 
<script> 
function loadXMLDoc(dname) 
{ 
if (window.XMLHttpRequest) 
    { 
    xhttp=new XMLHttpRequest(); 
    } 
else 
    { 
    xhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
xhttp.open("GET",dname,false); 
xhttp.send(""); 
return xhttp.responseXML; 
} 

function displayResult() 
{ 
xml=loadXMLDoc("f.xml"); 
xsl=loadXMLDoc("xsl.xsl"); 
// code for IE 
if (window.ActiveXObject) 
    { 
    ex=xml.transformNode(xsl); 
    document.getElementById("example").innerHTML=ex; 
    } 
// code for Mozilla, Firefox, Opera, etc. 
else if (document.implementation && document.implementation.createDocument) 
    { 
    xsltProcessor=new XSLTProcessor(); 
    xsltProcessor.importStylesheet(xsl); 

    xsltProcessor.setParameter(null, "testParam", "voo"); 
    // alert(xsltProcessor.getParameter(null,"voc")); 

    document.getElementById("example").innerHTML = ""; 

    resultDocument = xsltProcessor.transformToFragment(xml,document); 
    document.getElementById("example").appendChild(resultDocument); 
    } 


} 

</script> 
</head> 
<body onload="displayResult()"> 
    <li><u><a onclick="displayResult();" style="cursor: pointer;">test1</a></u></li> 
<div id="example" /> 
</body> 
</html> 

的XML

<?xml version="1.0" encoding="UTF-8"?> 
<?xml-stylesheet type="text/xsl" href="vocaroos.xsl"?> 
<test> 
    <artist name="Bert"> 
     <voo>bert1</voo> 
    </artist> 
    <artist name="Pet"> 
     <voo>pet1</voo> 
    </artist> 
</test> 

XSL

<?xml version="1.0" encoding="ISO-8859-1"?> 
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 

<xsl:param name="testParam"/> 
<xsl:template match="/"> 
    <html> 
    <body > 
    <h2>Titleee</h2> 
    <table border="1"> 
    <tr bgcolor="#9acd32"> 
     <th>Teeeeeest</th> 
    </tr> 
    <xsl:for-each select="test/artist"> 
    <tr> 
     <td><xsl:value-of select="$testParam"/></td> 
    </tr> 
    </xsl:for-each> 
    </table> 
    </body> 
    </html> 
</xsl:template> 
</xsl:stylesheet> 

下面是结果(左)

outcome

在左边是这是什么,在右边,我真正想要的。我期待的是

<xsl:value-of select="$testParam"/> 

会做同样的

<xsl:value-of select="voo"/>  (right outcome) 

,因为我做的setParameter(NULL, “testParam”, “VOO”);在html中,但由于某些原因,xsl不使用“voo”作为select,而是写入“voo”。

我一直在尝试不同的事情,但没有任何工作。错误在哪里?

回答

2

参数的值是字符串“voo”,这就是为什么应用于该参数的xsl:value-of返回字符串“voo”。没有理由期望XSLT处理器将“voo”视为要评估的XPath表达式。

如果参数的值是一个元素名称,并且您希望选择具有该名称的元素,则可以执行类似于select =“* [name()= $ testParam]”的操作。如果它是一个更一般的XPath表达式,那么你将需要一个xx:evaluate()扩展。

+0

谢谢,select =“* [name()= $ testParam]”正是我所需要的。我认为写入select =“voo”只会传递一个字符串,在这种情况下是“voo”,然后XSLT将采用该字符串并将其用作XPath表达式来评估。这就是为什么我认为我可以简单地给一个字符串选择一个参数。感谢您的解释。 –

1

XSLT不会在1.0或2.0中进行动态评估。某些扩展功能(如saxon:evaluate)会允许这样做,但它们的可用性取决于您正在使用的XSLT引擎。 XSLT 3.0建议在本地添加了xsl:evaluate,但有很少的XSLT引擎已经实现了3.0支持(saxon就是其中之一)。

+0

谢谢,我应该遇到更多的复杂问题,我可能不会使用XSLT,因为我真的只是想以某种格式快速显示某些数据用于测试目的。 –