2011-04-07 71 views
2

假設我有這樣的XML:如何使用xslt過濾xml中的節點..?

<college> 
    <student> 
     <name>amit</name> 
     <file>/abc/kk/final.c</file> 
     <rollno>22</rollno> 
    </student> 
    <student> 
     <name>sumit</name> 
     <file>/abc/kk/up.h</file> 
     <rollno>23</rollno> 
    </student> 
    <student> 
     <name>nikhil</name> 
     <file>/xyz/up.cpp</file> 
     <rollno>24</rollno> 
    </student> 
    <student> 
     <name>bharat</name> 
     <file>/abc/kk/down.h</file> 
     <rollno>25</rollno> 
    </student> 
    <student> 
     <name>ajay</name> 
     <file>/simple/st.h</file> 
     <rollno>27</rollno> 
    </student> 
</college> 

我使用的,在每一個「的.xsl」顯示節點的所有條目,但我只想要顯示這些節點的條目僅在文件名以「/ abc/kk」開頭,因爲我是xslt新手。

請爲我提供解決方案。

我使用:

<xsl:for-each select="college/student"> 
<tr> 
<td><xsl:value-of select="name"/></td> 
<td><xsl:value-of select="file"/></td> 
<td><xsl:value-of select="rollno"/></td> 
</tr> 
+1

請提供格式良好的XML,以便我們更好地理解您的問題 – 2011-04-07 09:07:56

+0

好問題,+1。查看我的答案,獲得使用XSLT的基本功能(例如模板和推式處理)的完整,簡短易用的解決方案。提供了詳細的解釋。 – 2011-04-07 13:30:44

回答

3

像這樣:

<xsl:for-each select="college/student[starts-with(file, '/abc/kk')]"> 
<!-- ... --> 

括號[ ]劃定一個 「過濾器」,而過濾器內,你可以有一個像starts-with()

+0

+1,做得很好。 – 2011-04-07 09:23:39

+0

非常感謝謝謝。 – kuldeep 2011-04-07 09:36:50

+0

@kuldeep:請檢查此答案是否正確。它會幫助你讓更多的人願意回答你關於SO的進一步問題。 – khachik 2011-04-07 09:47:59

0

你也功能可以使用[..]中的match

+0

非常感謝。 – kuldeep 2011-04-07 09:37:26

5

這種轉變

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:output omit-xml-declaration="yes" indent="yes"/> 
<xsl:strip-space elements="*"/> 


<xsl:template match="student[starts-with(file,'/abc/kk')]"> 
    <tr><xsl:apply-templates/></tr> 
</xsl:template> 

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

<xsl:template match="student"/>  
</xsl:stylesheet> 

當應用於提供的XML文檔:

<college> 
    <student> 
     <name>amit</name> 
     <file>/abc/kk/final.c</file> 
     <rollno>22</rollno> 
    </student> 
    <student> 
     <name>sumit</name> 
     <file>/abc/kk/up.h</file> 
     <rollno>23</rollno> 
    </student> 
    <student> 
     <name>nikhil</name> 
     <file>/xyz/up.cpp</file> 
     <rollno>24</rollno> 
    </student> 
    <student> 
     <name>bharat</name> 
     <file>/abc/kk/down.h</file> 
     <rollno>25</rollno> 
    </student> 
    <student> 
     <name>ajay</name> 
     <file>/simple/st.h</file> 
     <rollno>27</rollno> 
    </student> 
</college> 

產生想要的,正確的結果:

<tr> 
    <td>amit</td> 
    <td>/abc/kk/final.c</td> 
    <td>22</td> 
</tr> 
<tr> 
    <td>sumit</td> 
    <td>/abc/kk/up.h</td> 
    <td>23</td> 
</tr> 
<tr> 
    <td>bharat</td> 
    <td>/abc/kk/down.h</td> 
    <td>25</td> 
</tr> 

說明

  1. 模板匹配任何studentfile孩子,他的字符串值 '/ ABC/KK'開始。這只是將生成的內容放入包裝器tr元素中。

  2. 模板匹配任何student不具有體並有效地將其刪除(不復制此元件的輸出)。該模板的優先級低於第一個,因爲第一個模板更具體。因此,只有第一個模板未匹配的student元素才與第二個模板一起處理。

  3. 匹配任何student元素的子元素的模板。這只是將內容包裝到td元素中。

+0

+1正確的XSLT樣式。 – 2011-04-07 17:03:32