1

I need to do a conditional sum using XSLT. The sum of 'Oty' for each 'SKU' should be calculated only for providers listed within the 'Provider' node. In the provided example, the Qty for providerCode 4 should be skipped as its not in the 'Providers' list. I'm restricted to using XSLT 1.0.

I would appreciate any help. Thanks!

Here is the sample XML.

<?xml version="1.0" encoding="UTF-8"?>
<Root>
    <Providers>
        <ProviderCode>1</ProviderCode>
        <ProviderCode>2</ProviderCode>
        <ProviderCode>3</ProviderCode>        
    </Providers>
    <SKU>
        <SKU>XYZ</SKU>
        <Description>XYZ Description</Description>
        <Provider>
            <ProviderCode>1</ProviderCode>
            <Qty>100</Qty>
        </Provider>
        <Provider>
            <ProviderCode>2</ProviderCode>
            <Qty>67</Qty>
        </Provider>
        <Provider>
            <ProviderCode>3</ProviderCode>
            <Qty>74</Qty>
        </Provider>
        <Provider>
            <ProviderCode>4</ProviderCode>
            <Qty>62</Qty>
        </Provider>    
    </SKU>
    <SKU>
        <SKU>ABC</SKU>
        <Description>ABC Description</Description>
        <Provider>
            <ProviderCode>1</ProviderCode>
            <Qty>20</Qty>
        </Provider>
        <Provider>
            <ProviderCode>2</ProviderCode>
            <Qty>77</Qty>
        </Provider>
        <Provider>
            <ProviderCode>3</ProviderCode>
            <Qty>42</Qty>
        </Provider>    
        <Provider>
            <ProviderCode>4</ProviderCode>
            <Qty>631</Qty>
        </Provider>    
    </SKU>    
</Root>

Here is the required output.

<?xml version="1.0" encoding="UTF-8"?>
<Root>
    <SKU>
        <SKU>XYZ</SKU>
        <Qty>241</Qty>
    </SKU>
    <SKU>
        <SKU>ABC</SKU>
        <Qty>139</Qty>
    </SKU>    
</Root>
4

1 に答える 1

3

sum比較するsum(Provider[ProviderCode = //Providers/ProviderCode]/Qty)か、キーを使用して、必要なノードで簡単に使用できます。

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

<xsl:output indent="yes"/>

<xsl:key name="prov" match="Providers/ProviderCode" use="."/>

<xsl:template match="Root">
  <xsl:copy>
    <xsl:apply-templates select="SKU"/>
  </xsl:copy>
</xsl:template>

<xsl:template match="Root/SKU">
  <xsl:copy>
    <xsl:copy-of select="SKU"/>
    <Qty><xsl:value-of select="sum(Provider[key('prov', ProviderCode)]/Qty)"/></Qty>
  </xsl:copy>
</xsl:template>

</xsl:stylesheet>
于 2013-07-05T17:56:53.173 に答える