XML:
<amenities>
<record>
<thekey>77</thekey>
<thevalue>Balcony</thevalue>
</record>
<record>
<thekey>75</thekey>
<thevalue>Cable</thevalue>
</record>
<record>
<thekey>35</thekey>
<thevalue>High Speed Internet</thevalue>
</record>
<record>
<thekey>16</thekey>
<thevalue>Fireplace</thevalue>
</record>
<record>
<thekey>31</thekey>
<thevalue>Garage</thevalue>
</record>
<record>
<thekey>32</thekey>
<thevalue>Phone</thevalue>
</record>
</amenities>我需要检查设施中的每一条记录,看看是否存在"35“(高速互联网)。便利设施的记录可能会有所不同。有时它会有35 (高速互联网),有时不会。我需要能够在XSLT中检查这一点。
发布于 2013-01-08 20:29:41
<xsl:template match="amenities[record[thekey = 35 and thevalue = 'High Speed Internet']]">high speed internet exists</xsl:template>
<xsl:template match="amenities[not(record[thekey = 35 and thevalue = 'High Speed Internet'])]">high speed internet does not exist</xsl:template>当然,您也可以编写一个与amenities元素匹配的模板,然后在其中使用xsl:if或xsl:choose,例如
<xsl:template match="amenities">
<xsl:choose>
<xsl:when test="record[thekey = 35 and thevalue = 'High Speed Internet']">exists</xsl:when>
<xsl:otherwise>does not exist</xsl:otherwise>
</xsl:choose>
</xsl:template>发布于 2013-01-08 21:11:39
表达式最简单的形式这个问题的解决方案是单个纯XPath表达式
/*/record[thekey = 35 and thevalue = 'High Speed Internet']这将选择所有record元素,这些元素是XML文档顶部元素的子元素,并且具有带有字符串值的thekey子元素,当转换为数字时,数字等于35,并且具有字符串值为字符串'High Speed Internet‘的thevalue子元素。
not 的所有 elements都具有此属性
/*/record[not(thekey = 35 and thevalue = 'High Speed Internet')]您可以通过简单地将相应的XPath表达式指定为xsl:apply-templates (推荐)或xsl:for-each指令的select参数来处理这些节点。
<xsl:apply-templates select="/*/record[thekey = 35 and thevalue = 'High Speed Internet']"/>注意到,仅仅使用从该xsl:template表达式派生的匹配模式指定一个 XPath ,根本不能保证模板将被选择用于执行 --这取决于模板是(显式地还是隐式地)被应用。
访问所有感兴趣的节点的一种有效的、仅限XSLT的方法是使用key 。
<xsl:key name="kRecByKeyAndVal" match="record" use="concat(thekey,'+',thevalue)"/>上面为所有record元素指定了一个索引,基于它们的thekey和thevalue子元素的连接(用适当的分隔符字符串('+')来消除歧义,保证不会出现在这些值中)。
然后,引用所有具有字符串值为'35‘的record thekey子元素和字符串值为’ thevalue‘的thekey子元素的所有高速互联网元素的方法是:
key('kRecByKeyAndVal', '35+High Speed Internet')当一个表达式被多次求值时,使用键可以给我们带来很大的效率(速度)。
https://stackoverflow.com/questions/14214733
复制相似问题