如何使用XSLT筛选XML中指定product_type的产品?
嘿,刚接触XSLT和XML的话,筛选特定类型的产品其实没那么复杂~我给你两种实用的方法,专门针对你要筛选“fan”的需求写的,你可以直接套用,之后换其他类型也很简单:
首先先补全你提供的XML示例(方便后续演示):
<?xml version="1.0" standalone="yes"?> <products> <product> <Id>7</Id> <product_type>mother board</product_type> <name>ATX Motherboard X1</name> </product> <product> <Id>8</Id> <product_type>fan</product_type> <name>CPU Cooling Fan F2</name> </product> <product> <Id>9</Id> <product_type>fan</product_type> <name>Case Fan F3</name> </product> </products>
方法1:在遍历中直接添加筛选条件
如果你已经有了显示全部产品的XSLT,这种方法改动最小,只需要在遍历节点时加个筛选条件:
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/"> <html> <body> <h2>Fan Products</h2> <ul> <!-- 核心:只选取product_type为'fan'的product节点 --> <xsl:for-each select="products/product[product_type='fan']"> <li> ID: <xsl:value-of select="Id" /> - Name: <xsl:value-of select="name" /> </li> </xsl:for-each> </ul> </body> </html> </xsl:template> </xsl:stylesheet>
关键逻辑:select="products/product[product_type='fan']"里的方括号部分是XPath条件筛选,意思是只匹配product节点中,product_type子节点的文本等于'fan'的那些。
方法2:用模板匹配实现精准筛选
这种方法更符合XSLT的模板化设计思想,结构更清晰,适合后续扩展:
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <!-- 匹配根节点,输出页面基础框架 --> <xsl:template match="/"> <html> <body> <h2>Fan Products</h2> <ul> <!-- 只对fan类型的product节点应用模板 --> <xsl:apply-templates select="products/product[product_type='fan']" /> </ul> </body> </html> </xsl:template> <!-- 专门匹配fan类型的product节点,定义显示格式 --> <xsl:template match="product[product_type='fan']"> <li> ID: <xsl:value-of select="Id" /> - Name: <xsl:value-of select="name" /> </li> </xsl:template> <!-- 可选:忽略其他类型的product节点,避免默认输出冗余文本 --> <xsl:template match="product" /> </xsl:stylesheet>
扩展到其他类型
如果要为mother board单独做XSLT,只需要把上面代码里的'fan'全部替换成'mother board'就可以了,完全复用这套结构。
内容的提问来源于stack exchange,提问作者wizzone
相关产品推荐
相关产品推荐

