1

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 中检查这一点。

4

2 回答 2

1

在 XSLT 中有多种编写条件的方法,听起来好像您只是想编写一个匹配您的条件而另一个不匹配它的模式:

<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:iforxsl: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-08T12:29:41.203 回答
0

在最简单的形式中,这个问题的解决方案是一个单一的、纯 XPath 表达式

/*/record[thekey = 35 and thevalue = 'High Speed Internet']

这将选择record作为 XML 文档顶部元素的子元素并且thekey具有字符串值的子元素(当转换为数字时等于 35 并且具有thevalue字符串值为字符串“高速互联网”的子元素)的所有元素.

所有具有此属性的record元素

/*/record[not(thekey = 35 and thevalue = 'High Speed Internet')]

您可以通过简单地将相应的 XPath 表达式指定为(推荐的)或指令的select参数来处理这些节点。xsl:apply-templatesxsl:for-each

<xsl:apply-templates select="/*/record[thekey = 35 and thevalue = 'High Speed Internet']"/>

请注意,仅xsl:template使用从该 XPath 表达式派生的匹配模式指定 an 并不能保证选择执行该模板——这取决于是否应用了模板(显式或隐式)。

访问所有感兴趣的节点的一种有效的、仅限 XSLT 的方法是使用key

<xsl:key name="kRecByKeyAndVal" match="record" use="concat(thekey,'+',thevalue)"/>

以上为所有元素指定了一个索引record,基于它们thekeythevalue子元素的连接(通过合适的分隔符字符串 ('+') 消除歧义,保证不会出现在这些值中)。

然后,引用具有字符串值为“35”的子元素和字符串值为“高速互联网”的子元素的所有record元素thekeythevalue的方法是:

key('kRecByKeyAndVal', '35+High Speed Internet')

每当要多次计算表达式时,使用键给我们带来了极大的效率(速度)。

于 2013-01-08T13:11:38.527 回答