问题
I have a requirement like below:
In XSLT, I have a requirement like adding all MSPFEE amount under Invoice element based on FieldglassInvoiceId element, means if FieldglassInvoiceId is same then i need to consider only one the first MSP .
Input:
<Invoices xmlns="http://TargetNamespace.com/Invoices_FTP">
<Invoice>
<ConsolidatedInvoiceID>ONE</ConsolidatedInvoiceID>
<FieldglassInvoiceID>123</FieldglassInvoiceID>
<GrossInvoiceAmount>1600.00</GrossInvoiceAmount>
<NetInvoiceAmount>1600.00</NetInvoiceAmount>
<InvoiceAdjustmentAmount>0.00</InvoiceAdjustmentAmount>
<MSPFee>40.00</MSPFee>
<MSPFeeAdjustmentAmount>0.00</MSPFeeAdjustmentAmount>
</Invoice>
<Invoice>
<ConsolidatedInvoiceID>ONE</ConsolidatedInvoiceID>
<FieldglassInvoiceID>123</FieldglassInvoiceID>
<GrossInvoiceAmount>1600.00</GrossInvoiceAmount>
<NetInvoiceAmount>1600.00</NetInvoiceAmount>
<InvoiceAdjustmentAmount>0.00</InvoiceAdjustmentAmount>
<MSPFee>40.00</MSPFee>
<MSPFeeAdjustmentAmount>0.00</MSPFeeAdjustmentAmount>
</Invoice>
<Invoice>
<ConsolidatedInvoiceID>ONE</ConsolidatedInvoiceID>
<FieldglassInvoiceID>456</FieldglassInvoiceID>
<GrossInvoiceAmount>1600.00</GrossInvoiceAmount>
<NetInvoiceAmount>1600.00</NetInvoiceAmount>
<InvoiceAdjustmentAmount>0.00</InvoiceAdjustmentAmount>
<MSPFee>40.00</MSPFee>
<MSPFeeAdjustmentAmount>0.00</MSPFeeAdjustmentAmount>
</Invoice>
<Invoice>
<ConsolidatedInvoiceID>ONE</ConsolidatedInvoiceID>
<FieldglassInvoiceID>789</FieldglassInvoiceID>
<GrossInvoiceAmount>1600.00</GrossInvoiceAmount>
<NetInvoiceAmount>1600.00</NetInvoiceAmount>
<InvoiceAdjustmentAmount>0.00</InvoiceAdjustmentAmount>
<MSPFee>40.00</MSPFee>
<MSPFeeAdjustmentAmount>0.00</MSPFeeAdjustmentAmount>
</Invoice>
</Invoices>
Required Output:
<Invoices xmlns="http://TargetNamespace.com/Invoices_FTP">
<Invoice>
<Amount>180</Amount> -- Addition of all first MSPFEE element from all FieldGlassInvoiceId under one ConsolidatedInvoiceID
</Invoice>
</Invoices>
回答1:
First, please make sure I understand your question. You're looking for the sum of each <Invoice>
's <MSPFee>
value, but only for those <Invoice>
's that have the first instance of a unique <FieldglassInvoiceID>
value.
This should work:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns="http://TargetNamespace.com/Invoices_FTP"
xpath-default-namespace="http://TargetNamespace.com/Invoices_FTP"
exclude-result-prefixes="xs"
version="2.0">
<xsl:template match="/">
<Invoices>
<Amount>
<xsl:variable name="amounts" as="xs:double *">
<xsl:for-each-group select="Invoices/Invoice" group-by="xs:double(FieldglassInvoiceID)">
<xsl:sequence select="xs:double(MSPFee)"/>
</xsl:for-each-group>
</xsl:variable>
<xsl:value-of select="sum($amounts)"/>
</Amount>
</Invoices>
</xsl:template>
</xsl:stylesheet>
来源:https://stackoverflow.com/questions/43138468/in-xslt-i-have-a-requirement-like-adding-all-mspfee-amount-under-invoice-elemen