LinkedIn

Monday, May 30, 2011

Eliminating Duplicate Element set using XSLT and XPath

In my previous blogpost here I had described how to remove duplicate element sets from a XML collection using XQuery and XPath constructs.

Well in case you would need to use XSLT this can be achieved relatively much easier.

Here is the XSLT that can be used to remove all duplicate elements from an xml collection for the same example.

<xsl:stylesheet version="1.0" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" exclude-result-prefixes="xsl xsd">
<xsl:template match="/">
<FaultLogCollection>
<xsl:for-each select="/FaultLogCollection/FaultLog[not(faultCode=following::faultCode)]">
<xsl:sort select="./faultCode" order="ascending"/>
<FaultLog>
<xsl:copy-of select="./faultCode"/>
<xsl:copy-of select="./faultText"/>
<xsl:copy-of select="./faultSeverity"/>
<xsl:copy-of select="./faultingServiceName"/>
<xsl:copy-of select="./faultLogId"/>
</FaultLog>
</xsl:for-each>
</FaultLogCollection>
</xsl:template>
</xsl:stylesheet>

You can create an XSLT resource in Eclipse and copy paste the above to see this example running. See below to see how

image

image

Use the same input XML for FaultCollection

<FaultLogCollection>
<FaultLog>
<faultCode>001</faultCode>
<faultText>SystemFault</faultText>
<faultSeverity>High</faultSeverity>
<faultingServiceName>OrderProcessingPipeline</faultingServiceName>
<faultLogId>23</faultLogId>
</FaultLog>
<FaultLog>
<faultCode>001</faultCode>
<faultText>SystemFault</faultText>
<faultSeverity>High</faultSeverity>
<faultingServiceName>OrderProcessingPipeline</faultingServiceName>
<faultLogId>23</faultLogId>
</FaultLog>
<FaultLog>
<faultCode>002</faultCode>
<faultText>SystemFault</faultText>
<faultSeverity>High</faultSeverity>
<faultingServiceName>OrderProcessingPipeline</faultingServiceName>
<faultLogId>23</faultLogId>
</FaultLog>
<FaultLog>
<faultCode>002</faultCode>
<faultText>SystemFault</faultText>
<faultSeverity>High</faultSeverity>
<faultingServiceName>OrderProcessingPipeline</faultingServiceName>
<faultLogId>23</faultLogId>
</FaultLog>
</FaultLogCollection>

And here is the output after running the XSL.

image

Pretty easy. Does the same work as the XQuery in the previous example.

No comments:

Post a Comment