2012-02-08 80 views
1

以下是我正在嘗試執行的操作: 我有一個Faculties列表,其中每個列表都是一個部門列表。我想顯示整個部門列表,按部門名稱排序,但表示教職員。在嵌套對象中排序XSLT For Each

的XML看起來是這樣的:

<Faculties> 

    <Faculty Name="Science"> 
    <Department name="dept2"> 
     <head>Mr X</head> 
     <building>A Block</building> 
     etc... 
    </Department> 
    <Department name="dept3"> 
     <head>Mr X</head> 
     <building>B Block</building> 
     etc... 
    </Department> 
    </Faculty> 

    <Faculty Name="Education"> 
    <Department name="dept1"> 
     <head>Mr Y</head> 
     <building>C Block</building> 
     etc... 
    </Department> 
    </Faculty> 

</Faculties>  

的XSLT看起來是這樣的:(我已經簡化爲解釋的目的,XSLT)

<xsl:for-each select="Faculties"> 
    <xsl:sort select="DepartmentName"> 
    <xsl:for-each select="Departments"> 
    <xsl:element name="div"> 
     <xsl:attribute name="id"><xsl:value-of select="facultName"></xsl:attribute> 
     <h3><xsl:value-of select="deptName"> - <xsl:value-of select="facultName"></h3> 
     //More stuff here 
    </xsl:element> 
    </xsl:for-each> 
</xsl:for-each> 

想我的輸出看起來像:

Dept1 (Education) 
Head: Mr Y 
Building: C Block 

Dept2 (Science) 
Head: Mr X 
Building: A Block 

Dept3 (Science) 
Head: Mr X 
Building: B Block 

它按部門名稱排序。

我也希望能夠使用Javascript隱藏來自特定教師的所有部門,即隱藏所有具有特定教師身份的div。

我甚至不確定我所嘗試的是否可能(或合乎邏輯)。我唯一的其他選擇似乎是生成一個全新的部門名單,其中教員是其中一個要素。那我只需要一個for-each。不幸的是,我無法真正控制如何生成XML,所以我希望能夠這樣做。

我很感激任何幫助。謝謝!

+0

請編輯該問題並提供您忘記顯示的源XML文檔。另外,請提供轉換的確切結果。 – 2012-02-08 14:18:45

回答

6

如果要列出所有部門名稱順序,無論是教師,你可以簡單地在部門迭代直接

<xsl:for-each select="Faculty/Department"> 
    <xsl:sort select="@deptName" /> 

</xsl:for-each> 

然後,爲部門得到教員的名字,你可以訪問父元素很容易

<xsl:value-of select="../@facultyName" /> 

因此,假設您有以下XML

<Faculties> 
    <Faculty id="1" facultyName="Beer Drinking"> 
     <Department id="1" deptName="Real Ale" /> 
     <Department id="2" deptName="Lager" /> 
    </Faculty> 
    <Faculty id="2" facultyName="Food"> 
     <Department id="3" deptName="Fish and Chips" /> 
     <Department id="4" deptName="Pies" /> 
    </Faculty> 
</Faculties> 

當您應用以下XSLT

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:output method="html" indent="yes"/> 

    <xsl:template match="/Faculties"> 
     <xsl:apply-templates select="Faculty/Department"> 
     <xsl:sort select="@deptName" /> 
     </xsl:apply-templates> 
    </xsl:template> 

    <xsl:template match="Department"> 
     <div id="{../@facultyName}"> 
     <h3><xsl:value-of select="concat(@deptName, ' - ', ../@facultyName)" /></h3> 
     </div> 
    </xsl:template> 
</xsl:stylesheet> 

以下是輸出

<div id="Food"> 
    <h3>Fish and Chips - Food</h3> 
</div> 
<div id="Beer Drinking"> 
    <h3>Lager - Beer Drinking</h3> 
</div> 
<div id="Food"> 
    <h3>Pies - Food</h3> 
</div> 
<div id="Beer Drinking"> 
    <h3>Real Ale - Beer Drinking</h3> 
</div> 

做筆記,通常最好使用XSL:申請模板的xsl:for-每個,所以這就是我在XSLT中使用的。

+0

哇,太棒了!非常感謝!感謝您的快速回復。您的解決方案非常優雅。 – 2012-02-08 15:01:21

+0

只需將您的解決方案應用到我的項目中,它就像魅力一樣。再次感謝! – 2012-02-08 15:08:21