如何使用 XSLT 将 XML 节点出现计数为 for-each 或 xsl:template?

How to count XML node occurence into a for-each or xsl:template using XSLT?

我想计算 XML 节点的每次出现次数,其中包含我只能通过读取节点知道的动态特定值。

我第一次尝试用 for-each 尝试用 XPath 计算 xml 节点,但它似乎在当前行中被阻塞,无法计算出现次数。

现在有了 xsl:template,我以为我可以提取正确的值,但我做不到。

XML 输入:

<?xml version="1.0" encoding="UTF-8"?>
<XMLCreators>
    <row>
        <element0>0313409760492014833</element0>
    </row>
    <row>
        <element0>0310709773371838642</element0>
    </row>
    <row>
        <element0>0313809763241653098</element0>
    </row>
    <row>
        <element0>0115709728654070781</element0>
    </row>
    <row>
        <element0>0110009760492014833</element0>
    </row>
</XMLCreators>

我需要的输出:

<liste xmlns:java="http://xml.apache.org/xslt/java">
   <nm id="760492014833">
      <count>2</count>
   </nm>
   <nm id="773371838642">
      <count>1</count>
   </nm>
   <nm id="763241653098">
      <count>1</count>
   </nm>
   <nm id="728654070781">
      <count>1</count>
   </nm>
   <nm id="760492014833">
      <count>2</count>
   </nm>
</liste>

我的 XSLT 输出

<liste xmlns:java="http://xml.apache.org/xslt/java">
   <nm id="760492014833">
      <count>0</count>
   </nm>
   <nm id="773371838642">
      <count>0</count>
   </nm>
   <nm id="763241653098">
      <count>0</count>
   </nm>
   <nm id="728654070781">
      <count>0</count>
   </nm>
   <nm id="760492014833">
      <count>0</count>
   </nm>
</liste>

我的 XSLT:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:java="http://xml.apache.org/xslt/java">
    <xsl:output method="xml" encoding="UTF-8" indent="yes" doctype-public="-//W3C//DTD XHTML 1.0 Strict//EN" /> 
    <xsl:template match="/">
    <liste>
        <xsl:apply-templates/>
    </liste>
    </xsl:template>

    <xsl:template match="XMLCreators">
        <xsl:apply-templates select="row"/>
    </xsl:template>

    <xsl:template match="row">
        <xsl:apply-templates select="element0"/>
    </xsl:template>

    <xsl:template match="element0">
        <xsl:variable name="idNM" select="normalize-space(substring(., 8, 14))" />
        <nm>
            <xsl:attribute name="id">
                <xsl:value-of select="$idNM"/>
            </xsl:attribute>
            <count>
                <xsl:value-of select="count(//*[contains(element0,'$idNM')])" />
            </count>
        </nm>
    </xsl:template>
</xsl:stylesheet>

您需要删除 contains 中变量使用周围的撇号,否则它会逐字查找字符串“$idNM”而不是变量的值

 <xsl:value-of select="count(//*[contains(element0,$idNM)])" />

你真的想在这里使用 contains 吗,因为这也会计算字符串开头的元素?如果您只想计算最后出现的字符串,请执行此操作...

<xsl:value-of select="count(//*[substring(element0, 8, 14) = $idNM])" />