如何在XSLT中进行模式匹配并添加值

时间:2013-07-15 00:27:59

标签: xslt

作为XSLT的一部分,我需要添加“Duration”元素的所有值并显示值。现在,下面的XML是我正在研究的更大的XML的一部分。在下面的XML中,我需要匹配 a / TimesheetDuration / Day * / Duration,添加值并显示它们。我不想将所有值存储在变量中并添加它们。还有其他干净的方法吗?

<?xml version="1.0" ?>
<a>
<TimesheetDuration>
  <Day1>
    <BusinessDate>6/12/2013</BusinessDate>
    <Duration>03:00</Duration>
  </Day1>
  <Day2>
    <BusinessDate>6/13/2013</BusinessDate>
    <Duration>04:00</Duration>
  </Day2>
  <Day3>
    <BusinessDate>6/14/2013</BusinessDate>
    <Duration>05:00</Duration>
  </Day3>
</TimesheetDuration>
</a>

2 个答案:

答案 0 :(得分:1)

XPath 2.0解决方案(假设持续时间采用HH:MM格式)将为

sum(for $d in a//Duration 
    return xs:dayTimeDuration(replace($d, '(..):(..)', 'PT$1H$2M')))

答案 1 :(得分:0)

在xslt 1.0中,您可以使用以下样式表

来执行此操作
<?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" version="1.0" encoding="UTF-8" indent="yes"/>

    <xsl:template match="/">
        <Durations>
            <xsl:apply-templates select="a/TimesheetDuration/node()[starts-with(name(),'Day')]" />


        <xsl:variable name="hours">
            <xsl:call-template name="sumHours">
                <xsl:with-param name="Day" select="a/TimesheetDuration/node()[starts-with(name(),'Day')][1]" />
            </xsl:call-template>
        </xsl:variable>

        <SumOfHours>
            <xsl:value-of select="$hours" />
        </SumOfHours>
        <!-- Sum of minutes would be calculated similarly -->
        </Durations>

    </xsl:template>

    <xsl:template match="node()[starts-with(name(),'Day')]">
        <xsl:copy-of select="Duration" />
    </xsl:template>

    <xsl:template name="sumHours">
        <xsl:param name="tmpSum" select="0" />
        <xsl:param name="Day" />

        <xsl:variable name="newTmpSum" select="$tmpSum + substring-before($Day/Duration, ':')" />
        <xsl:choose>
            <xsl:when test="$Day/following-sibling::node()[starts-with(name(),'Day')]">
                <xsl:call-template name="sumHours">
                    <xsl:with-param name="tmpSum" select="$newTmpSum" />
                    <xsl:with-param name="Day" select="$Day/following-sibling::node()[starts-with(name(),'Day')]" />
                </xsl:call-template>
            </xsl:when>
            <xsl:otherwise>
                <xsl:value-of select="$newTmpSum" />
            </xsl:otherwise>
        </xsl:choose>

    </xsl:template>
</xsl:stylesheet>

它产生输出

<?xml version="1.0" encoding="UTF-8"?>
<Durations>
    <Duration>03:00</Duration>
    <Duration>04:00</Duration>
    <Duration>01:00</Duration>
    <SumOfHours>8</SumOfHours>
</Durations>