计算与XML中的字符串模式匹配的节点

时间:2016-04-13 04:04:08

标签: xml xslt

如何计算单词LISTBUYSELL在此XML文档的chart_name节点中的次数?我试图找出父节点test_name中每个节点列出的次数。

<?xml version="1.0" encoding="utf-8"?>
<digital1>
  <test_name ID="Test">
    <record>
      <chart_name>LIST OR BUY Test 1</chart_name>
    </record>
    <record>
      <chart_name>LIST Test 2</chart_name>
    </record>
  </test_name>
  <test_name ID="Ryan">
    <record>
      <chart_name>BUY Ryan 1</chart_name>
    </record>
    <record>
      <chart_name>LIST Ryan 2</chart_name>
    </record>
    <record>
      <chart_name>SELL OR LIST Ryan 3</chart_name>
    </record>
    <record>
      <chart_name>LIST OR BUY Ryan 4</chart_name>
    </record>
    <record>
      <chart_name>BUY Ryan 5</chart_name>
    </record>
    <record>
      <chart_name>LIST Ryan 6</chart_name>
    </record>
  </test_name>
</digital_tpp>

我使用的XSLT文件如下所示:          

<xsl:template match="/">
  <html>
  <body>
  <h2>My Test File</h2>
      <xsl:for-each select="digital1/test_name/record]">
        <tr>
          <td><xsl:value-of select="../@ID"/></td>
          <td><xsl:value-of select="count(chart_name[. Like '*LIST*'])"/></td>
        </tr>
      </xsl:for-each>
    </table>
  </body>
  </html>
</xsl:template>

这条线<td><xsl:value-of select="count(chart_name[. Like '*LIST*'])"/></td>我需要帮助。如何进行模式匹配以匹配上面的关键词?

输出将是一个表格,显示test_name ID,LIST计数,买入次数和卖出次数。

1 个答案:

答案 0 :(得分:2)

如果我理解正确,你想做:

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

<xsl:template match="/digital1">
    <html>
        <body>
            <h2>My Test File</h2>
            <table border="1">
                <tr>
                    <th>ID</th>
                    <th>LIST</th>
                    <th>BUY</th>
                    <th>SELL</th>
                </tr>
                <xsl:for-each select="test_name">
                    <tr>
                        <td>
                            <xsl:value-of select="@ID"/>
                        </td>
                        <td>
                            <xsl:value-of select="count(record[contains(chart_name, 'LIST')])"/>
                        </td>
                        <td>
                            <xsl:value-of select="count(record[contains(chart_name, 'BUY')])"/>
                        </td>
                        <td>
                            <xsl:value-of select="count(record[contains(chart_name, 'SELL')])"/>
                        </td>
                    </tr>
                </xsl:for-each>
            </table>
        </body> 
    </html>
</xsl:template>

</xsl:stylesheet>

应用于您的输入示例(在将</digital_tpp>更正为</digital1>后),结果将为:

enter image description here