如何使用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>
答
这种转变:
<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>
说明:
模板匹配任何
student
有file
孩子,他的字符串值 '/ ABC/KK'开始。这只是将生成的内容放入包装器tr
元素中。模板匹配任何
student
不具有体并有效地将其删除(不复制此元件的输出)。该模板的优先级低于第一个,因为第一个模板更具体。因此,只有第一个模板未匹配的student
元素才与第二个模板一起处理。匹配任何
student
元素的子元素的模板。这只是将内容包装到td
元素中。
+0
+1正确的XSLT样式。 – 2011-04-07 17:03:32
请提供格式良好的XML,以便我们更好地理解您的问题 – 2011-04-07 09:07:56
好问题,+1。查看我的答案,获得使用XSLT的基本功能(例如模板和推式处理)的完整,简短易用的解决方案。提供了详细的解释。 – 2011-04-07 13:30:44