XSLT使用逗号分隔符获取匹配的数据

时间:2010-01-15 09:13:02

标签: xslt

我的数据如下:

<ProductAttributes>
<Attribute>
  <ItemCode>ITEM-0174676</ItemCode> 
  <AttributeCode>host_interface</AttributeCode> 
  <AttributeDescription>Host Interface</AttributeDescription> 
  <AttributeValueCode>usb</AttributeValueCode> 
  <AttributeValueDescription>USB</AttributeValueDescription> 
  <GroupCode>technical_information</GroupCode> 
  <GroupDescription>Technical Information</GroupDescription> 
  <GroupPostion /> 
  <DisplayInList>True</DisplayInList> 
  <GroupPosition>1</GroupPosition> 
  </Attribute>
<Attribute>
  <ItemCode>ITEM-0174676</ItemCode> 
  <AttributeCode>host_interface</AttributeCode> 
  <AttributeDescription>Host Interface</AttributeDescription> 
  <AttributeValueCode /> 
  <AttributeValueDescription>USB</AttributeValueDescription> 
  <GroupCode>technical_information</GroupCode> 
  <GroupDescription>Technical Information</GroupDescription> 
  <GroupPostion /> 
  <DisplayInList>True</DisplayInList> 
  <GroupPosition>1</GroupPosition> 
  </Attribute>
<Attribute>

上面的xml <AttributeDescription><Attribute>节点中都有相同的文本,在这种情况下,我想显示如下所示的reslut,它将使用<AttributeValueDescription>节点,结果将是< / p>

主机接口:USB,USB

那么对结果有什么帮助?

提前致谢, 嗡

2 个答案:

答案 0 :(得分:2)

我假设你想要HTML作为输出。

您需要按<ItemCode>, <AttributeCode>对数据进行分组。这意味着复合Muenchian分组方法。你需要这把钥匙:

<xsl:key 
  name="AttributeByAttributeCode" 
  match="Attribute" 
  use="concat(ItemCode, '|', AttributeCode)" 
/>

然后,您可以使用密钥在<AttributeCode><ProductAttributes>分组:

<xsl:template match="ProductAttributes">
  <!-- check every attribute… -->
  <xsl:for-each select="Attribute">

    <!-- …select all attributes that share the same item and attribute codes -->
    <xsl:variable name="EqualAttributes" select="
      key('AttributeByAttributeCode', concat(ItemCode, '|', AttributeCode))
    " />

    <!-- make sure output is generated for the first of them only -->
    <xsl:if test="generate-id() = generate-id($EqualAttributes[1])">
      <div>
        <xsl:value-of select="AttributeDescription" />
        <xsl:text>: </xsl:text>
        <!-- now make a list out of any attributes that are equal -->
        <xsl:apply-templates mode="list" select="
          $EqualAttributes/AttributeValueDescription
        " />
      </div>
    </xsl:if>
  </xsl:for-each>
</xsl:template>

<!-- generic template to make a comma-separated list out of input elements -->
<xsl:template match="*" mode="list">
  <xsl:value-of select="." />
  <xsl:if test="position() &lt; last()">
    <xsl:text>, </xsl:text>
  </xsl:if>
</xsl:template>

以上将导致

<div>Host Interface: USB, USB</div>

答案 1 :(得分:1)

要构建以逗号分隔的字符串,您可以使用上一个问题:XSLT concat string, remove last comma