Brad
Brad

Reputation: 3

XSL compare elements in difference nodes and add the value of element in out put

I am trying to get a total of on hand items from two facility. I have tried several variations using xsl:template match="" and xsl:for-each select="" and have no luck and probable confused myself more at this point.

XML Structure:

    <Facility>
      <Id>92</Id>
      <Item>
        <Sku>10100200-99</Sku>
        <OnHand>623</OnHand>
      </Item>
      <Item>
        <Sku>10201400-00</Sku>
        <OnHand>509</OnHand>
      </Item>
    <Facility>
      <Id>99</Id>
      <Item>
        <Sku>10100100-99</Sku>
        <OnHand>0</OnHand>
      </Item>
      <Item>
        <Sku>10100200-99</Sku>
        <OnHand>725</OnHand>
      </Item>

Output wanted:

      <Item>
        <Sku>10100200-99</Sku>
        <OnHand>1348</OnHand>
      </Item>
      <Item>
        <Sku>10201400-00</Sku>
        <OnHand>509</OnHand>
      </Item>
      <Item>
        <Sku>10100100-99</Sku>
        <OnHand>0</OnHand>
      </Item>

On the output I would get all <Sku> with <OnHand> from <Facility[1]> and <Facility[2]> but if the <Sku> is in both then add the <OnHand> for a total. Any help is appreciated.

Upvotes: 0

Views: 67

Answers (1)

dlask
dlask

Reputation: 8982

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

    <xsl:output method="xml" indent="yes"/>

    <!-- define a set of Items identified by Sku -->
    <xsl:key name="groups" match="Item" use="Sku" />

    <xsl:template match="/">
        <root>
            <!-- select always only the first Item with the same Sku -->
            <xsl:apply-templates select=".//Item[generate-id() = generate-id(key('groups', Sku)[1])]"/>
        </root>
    </xsl:template>

    <xsl:template match="Item">
        <Item>
            <xsl:copy-of select="Sku"/>
            <OnHand>
                <!-- sum OnHand of all Items with the same Sku -->
                <xsl:value-of select="sum(key('groups', Sku)/OnHand)"/>
            </OnHand>
        </Item>
    </xsl:template>

</xsl:stylesheet>

Upvotes: 1

Related Questions