2017-01-09 10 views
0

Я новичок в XSLT и вам необходимо суммировать общую сумму (количество * UnitPrice) предметов на основе идентификатора из каждого заказа и распечатать ее в конце каждой группы элемента с помощью XSLT 1.0. Вот мой пример XMLXSLT группировка и суммирование

<Orders> 
<Order> 
    <Reference>234</Reference> 
    <Item> 
     <ID>10</ID> 
     <Quantity>1</Quantity> 
     <UnitPrice>2</UnitPrice> 
    </Item> 
    <Item> 
     <ID>10</ID> 
     <Quantity>2</Quantity> 
     <UnitPrice>3</UnitPrice> 
    </Item> 
    <Item> 
     <ID>10</ID> 
     <Quantity>2</Quantity> 
     <UnitPrice>2</UnitPrice> 
    </Item> 
    <Item> 
     <ID>20</ID> 
     <Quantity>2</Quantity> 
     <UnitPrice>4</UnitPrice> 
    </Item> 
</Order> 
<Order> 
    <Reference>456</Reference> 
    <Item> 
     <ID>10</ID> 
     <Quantity>2</Quantity> 
     <UnitPrice>2</UnitPrice> 
    </Item> 
    <Item> 
     <ID>20</ID> 
     <Quantity>2</Quantity> 
     <UnitPrice>2</UnitPrice> 
    </Item> 
</Order> 
</Orders> 

Нужный выход XML ниже

<SAPOrders> 
<Order> 
    <Reference>234</Reference> 
    <Item> 
     <Quantity>1</Quantity> 
     <UnitPrice>2</UnitPrice> 
    </Item> 
    <Item> 
     <Quantity>2</Quantity> 
     <UnitPrice>3</UnitPrice> 
    </Item> 
    <Item> 
     <Quantity>2</Quantity> 
     <UnitPrice>2</UnitPrice> 
     <Total>12</Notes> 
    </Item> 
    <Item> 
     <Quantity>2</Quantity> 
     <UnitPrice>4</UnitPrice> 
     <Total>8</Notes> 
    </Item> 
</Order> 
<Order> 
    <Reference>456</Reference> 
    <Item> 
     <Quantity>2</Quantity> 
     <UnitPrice>2</UnitPrice> 
     <Total>4</Notes> 
    </Item> 
    <Item> 
     <Quantity>2</Quantity> 
     <UnitPrice>2</UnitPrice> 
     <Total>4</Total> 
    </Item> 
</Order> 
</SAPOrders> 
+0

См http://stackoverflow.com/questions/37205574/sum-of-similar-elements-in-xslt, который является почти копией –

+1

@MichaelKay Вы указываете на решение XSLT 2.0. –

+1

@tojira Почему в выводе нет идентификаторов предметов? –

ответ

0

Есть две проблемы: (1) группа пункты по поручению и по идентификатору, и (2) вычислить промежуточный итог для каждой такой группы.

Первая проблема относительно проста и может быть решена с использованием метода Muenchian grouping. Вторая проблема сложнее, поскольку XSLT 1.0 не позволяет суммировать результат вычисления.

Следующая таблица стилей начинается с предварительного расчета расширенной цены каждого элемента и сохранения результатов в переменной. Затем он работает с переменной, группируя элементы и подтачивая каждую группу.

XSLT 1,0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
xmlns:exsl="http://exslt.org/common" 
extension-element-prefixes="exsl"> 
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/> 

<xsl:key name="item" match="Item" use="@key" /> 

<xsl:template match="/Orders"> 
    <!-- first pass --> 
    <xsl:variable name="first-pass"> 
     <xsl:for-each select="Order"> 
      <Order> 
       <xsl:copy-of select="Reference"/> 
       <xsl:for-each select="Item"> 
        <Item key="{concat(../Reference, '|', ID)}" extPrice="{Quantity * UnitPrice}"> 
         <xsl:copy-of select="*"/> 
        </Item> 
       </xsl:for-each> 
      </Order> 
     </xsl:for-each> 
    </xsl:variable> 
    <!-- output --> 
    <SAPOrders> 
     <xsl:for-each select="exsl:node-set($first-pass)/Order"> 
      <xsl:copy> 
       <xsl:copy-of select="Reference"/> 
       <!-- for each unique item in this order --> 
       <xsl:for-each select="Item[count(. | key('item', @key)[1]) = 1]"> 
        <!-- list the items in this group --> 
        <xsl:for-each select="key('item', @key)"> 
         <Item> 
          <xsl:copy-of select="Quantity | UnitPrice"/> 
          <!-- add the subtotal of this group --> 
          <xsl:if test="position()=last()"> 
           <Total> 
            <xsl:value-of select="sum(key('item', @key)/@extPrice)" /> 
           </Total> 
          </xsl:if> 
         </Item> 
        </xsl:for-each> 
       </xsl:for-each> 
      </xsl:copy> 
     </xsl:for-each> 
    </SAPOrders> 
</xsl:template> 

</xsl:stylesheet> 

Демо: http://xsltransform.net/jz1PuPz

+0

спасибо за решение! Это работает хорошо! – tojira

Смежные вопросы