如何使用xslt过滤xml中的节点..?

问题描述:

假设我有这样的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

像这样:

<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

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

+0

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

这种转变

<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