2012-11-11 56 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,因爲我真的只是想以某種格式快速顯示某些數據用於測試目的。 –