2013-07-15 21 views
0

作爲XSLT的一部分,我需要添加「持續時間」元素的所有值並顯示值。現在,下面的XML是我正在處理的更大XML的一部分。在下面的XML中,我需要匹配 a/TimesheetDuration/Day */Duration,添加值並顯示它們。我不想將所有值存儲在變量中並添加它們。有沒有其他乾淨的方式來做到這一點?如何在XSLT中模式匹配並添加值

<?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> 
+0

哪個st您是否打算使用ylesheet版本和xslt處理器? – 2013-07-15 02:27:44

+0

處理器:XslCompiledTransform。版本:更好,如果它是1.0。如果沒有,我可以用2.0來做。 – Feroz

回答

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> 
1

一個XPath 2.0溶液,假設持續時間的形式HH: MM,將是

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