XSLT用子字符串计算不同的上下文



我对XSLT有一个相当复杂的需求。我需要计算值等于其值的子字符串的字段。我能数出来,但问题是上下文。请参见下面的示例:

         <root>
            <Manager>TC4:12345</Manager>
            <Staff>
                <employee>TC3:22222</employee>
                <employee>TC3:11111</employee>
                <employee>TC3:33333</employee>
            </Staff>
            </root>
         <root>
            <Manager>TC4:67890</Manager>
            <Staff>
                <employee>TC3:44444</employee>
                <employee>TC3:55555</employee>
                <employee>TC3:66666</employee>
            </Staff>
            </root>

输出应该像这样:

            <Manager>
            <Seniors>
            <Count>3</Count>
            </Seniors>
            </Manager>
            <Manager>
            <Seniors>
            <Count>3</Count>
            </Seniors>
            </Manager>

计算第一个经理的TC3角色的员工数量,然后计算第二个经理的TC3角色的员工数量。我试过这样做,但我最终在第一个上下文中有6,在第二个上下文中也有6,而不是3和3。

这是我的代码

<xsl:value-of select="count(//root/Staff/employee[substring(.,1,3) = 'TC3'])">

就是这样(假设所有xml都用body标签包装):

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" omit-xml-declaration="yes" indent="yes" /> 
    <xsl:template match="body">
        <xsl:for-each select="root">
            <Manager>
            <Seniors>
                <Count><xsl:value-of select="count(./Staff/employee[substring(.,1,3) = 'TC3'])" /></Count>
            </Seniors>
            </Manager>
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>

下面是我使用的源代码:

<?xml version="1.0" encoding="UTF-8"?>
<body>
    <root>
        <Manager>TC4:12345</Manager>
        <Staff>
            <employee>TC3:22222</employee>
            <employee>TC3:11111</employee>
            <employee>TC3:33333</employee>
        </Staff>
        </root>
     <root>
        <Manager>TC4:67890</Manager>
        <Staff>
            <employee>TC3:44444</employee>
            <employee>TC3:55555</employee>
            <employee>TC3:66666</employee>
        </Staff>
   </root>
</body>

输出如下:

<Manager>
  <Seniors>
    <Count>3</Count>
  </Seniors>
</Manager><Manager>
  <Seniors>
    <Count>3</Count>
  </Seniors>
</Manager>

写一个模板match="root",然后在里面可以使用<xsl:value-of select="count(Staff/employee[substring(.,1,3) = 'TC3'])"/>

相关内容

  • 没有找到相关文章

最新更新