首页 > 解决方案 > xslt通过多个列值选择表行

问题描述

我得到了以下 XML:

    <?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
        <row>
          <column>
            <name>COL_A</name>
            <string>xxx</string>
          </column>
          <column>
            <name>COL_B</name>
            <currency>yyy</currency>
          </column>
          <column>
            <name>COL_C</name>
            <number>zzz</number>
          </column>
        </row>
        <row>
          <column>
            <name>COL_A</name>
            <string>aaa</string>
          </column>
          <column>
            <name>COL_B</name>
            <currency>bbb</currency>
          </column>
          <column>
            <name>COL_C</name>
            <number>ccc</number>
          </column>
          </row>
  </soap:Body>
</soap:Envelope>

我想检测是否存在具有三重列/值的行(COL_A = aaa 和 COL_B = bbb 和 COL_C = ccc)

我写了这个 xslt,但我只能匹配第一对并且不知道如何继续......

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:fn="http://www.w3.org/2005/xpath-functions">
    <xsl:template match="Envelope">
        <xsl:apply-templates select="/Body/row"/>
    </xsl:template>
    <xsl:template match="row">
        <xsl:choose>
            <xsl:when test="(column/name = 'COL_A') and (column/string = 'xxx' )">
                <xsl:text> Found </xsl:text>
            </xsl:when>
        </xsl:choose>
    </xsl:template>
</xsl:stylesheet>

我编写了该脚本以了解如何找到具有这些值的行(aaa、bbb、ccc)。之后,如果可能的话,我需要一个 xpath 语句来检查是否存在具有这些值的行。

标签: xsltsearchmultiple-columnsxmltable

解决方案


您可以and-combine 中的三个节点存在测试xsl:whenrow所以要匹配第二个

column[name = 'COL_A' and string = 'aaa'] and column[name = 'COL_B' and currency = 'bbb'] and column[name = 'COL_C' and number = 'ccc']

这个 XPath-1.0 表达式满足您的要求。


这是整个测试样式表:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">

    <xsl:template match="/soap:Envelope">
        <xsl:apply-templates select="soap:Body/row"/>
    </xsl:template>

    <xsl:template match="row">
        <xsl:choose>
            <xsl:when test="column[name = 'COL_A' and string = 'aaa'] and column[name = 'COL_B' and currency = 'bbb'] and column[name = 'COL_C' and number = 'ccc']">
                <xsl:text> Found </xsl:text>
            </xsl:when>
        </xsl:choose>
    </xsl:template>

</xsl:stylesheet>

推荐阅读