2013-11-26 70 views
0

這裏的基本XSLT問題需要幫助才能得到一個乾淨的解決方案。致電XSLT模板參考

我的XML

<class_list> 
<students> 
    <student> 
     <id>1</id> 
     <name>Aimee</name> 

    </student> 
    <student> 
     <id>2</id> 
     <name>Anna</name> 
    </student> 
<students> 
<tests> 
    <test> 
     <name>mathematics test 1</name> 
     <student_id>1</id> 
     <grade>A+</grade> 
    </test> 
    <test> 
     <name>mathematics test 1</name> 
     <student_id>1</id> 
     <grade>B+</grade> 
    </test> 
    <test> 
     <name>mathematics test 2</name> 
     <student_id>1</id> 
     <grade>B+</grade> 
    </test> 
    <test> 
     <name>mathematics test 2</name> 
     <student_id>2</id> 
     <grade>B+</grade> 
    </test> 
    <test> 
     <name>mathematics test 3</name> 
     <student_id>1</id> 
     <grade>B+</grade> 
    </test> 
<tests> 
</class_list> 

我喜歡有後續結果

艾梅

考數學1

考數學3

安娜

考數學1

考數學2

這是我的XSL

<xsl:template match="students"> 
<xsl:apply-templates select="student"/> 
</xsl:template> 

<xsl:template match="student"> 
<xsl:value-of select="name"/> 
<xsl:apply-templates select="/class_list/tests"/> 
</xsl:template> 

<xsl:template match="tests"> 
<xsl:value-of select="test[student_id=?id" /> 
</xsl:template> 

<xsl:template match="test"> 
<xsl:value-of select="name" /> 
</xsl:template> 

我的問題是如何能夠及格或過濾器 「測試」 與學生證[?ID]

謝謝

羅馬

回答

1

您al準備好了用方括號來過濾的想法,但它是不恰當的「價值的」,用它的「應用模板」,而不是像這樣:如果你想在目前的學生篩選

<xsl:template match="student"> 
    <xsl:value-of select="name"/> 
    <xsl:apply-templates select="/class_list/tests[student_id='1']"/> 
</xsl:template> 

,你可以使用一個變量來避免混淆數據:

<xsl:template match="student"> 
    <xsl:variable name="stud_id" select="id"/> 
    <xsl:value-of select="name"/> 
    <xsl:apply-templates select="/class_list/tests[student_id=$stud_id]"/> 
</xsl:template> 

沒有測試過這個,但它應該工作。
編輯完成:您也可以在「模板匹配」上過濾方括號。
編輯@Ian羅伯茨:偉大的想法,我不知道的電流()

+2

或者只是使用''然後根本不需要變量。 –

0

假設正確的輸入,請使用以下樣式

<?xml version="1.0" encoding="utf-8"?> 

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 

<xsl:output method="text" encoding="utf-8"/> 

<xsl:strip-space elements="*"/> 

<xsl:template match="/"> 
    <xsl:apply-templates/> 
</xsl:template> 

<xsl:template match="students"> 
<xsl:apply-templates/> 
</xsl:template> 

<xsl:template match="student"> 
    <xsl:variable name="id1" select="id"/> 
<xsl:value-of select="name"/> 
<xsl:text>&#10;</xsl:text> 
<xsl:for-each select="//test[student_id=$id1]/name"> 
    <xsl:value-of select="."/> 
    <xsl:text>&#10;</xsl:text> 
</xsl:for-each> 
</xsl:template> 

<xsl:template match="test"/> 

</xsl:stylesheet> 

這是輸出我得到這個:

Aimee 
mathematics test 1 
mathematics test 1 
mathematics test 2 
mathematics test 3 
Anna 
mathematics test 2 

請注意您輸入的XML是無效的XML。確保所有元素都正確關閉(例如students元素)。此外,student_id元素必須使用相同的標籤(即不是id)關閉。

我建議你檢查你的XML(和XSLT)對XML解析器或驗證器,以避免這種情況。