XSLT Distinct another way to determine distinct in XSLT 1.0

By patrickwellink
February 17, 2011
Comments Off on XSLT Distinct another way to determine distinct in XSLT 1.0

I had a requirement to map a buyer only if it was the same buyer throughout the entire document.
The reason for this was that in the source document the buyer was defined in a sub sub sub node of a document and in the destination it occurred only once.
So I ended up with several choices.

  • Only map the first buyer
  • Don’t map
  • Only map if they were the same throughout the entire document

For sure the first option would be a bad thing.
The second option would work for all parties involved (it’s an optional element in the output of the map) but the parties really want their buyer information if it’s there.
The third option seemed the best solution. I quickly googled on XSLT and distinct and there were some results. So I told the customer implementing a distinct wouldn’t be too hard. (it already existed in XSLT).
(I wish I looked a bit harder, cause then I would have seen that the distinct function of XSLT comes with XSLT 2.0 and sadly BizTalk is still using XSLT1.0)

After some thinking I got the following solution for this problem.

  1. Perform a count of the number of buyers in a document
  2. Get the first buyer (buyer is mandatory in the input document)
  3. Perform a count of the numbers of buyers where buyer != buyer found in step2

If the number in step 3 is 0 then we know all the buyers are the same. Below is the XSLT I used to perform this different distinct approach.

<xsl:template name=”Buyerparty_DocTemplate”>
  <xsl:param name=”var1″ />
  <xsl:param name=”var2″ />
  <xsl:param name=”dbg” />
  <xsl:variable name=”buyers” select=”count(/s0:Request/GeleverdePartij/LeveringsBericht/Levering[*]/Ladingdrager[*]/Goederen[*]/Koper/kop_gln)” />
  <xsl:variable name=”firstBuyer” select=”/s0:Request/GeleverdePartij/LeveringsBericht/Levering[1]/Ladingdrager[1]/Goederen[1]/Koper/kop_gln” />
  <xsl:variable name=”otherBuyers” select=”count(/s0:Request/GeleverdePartij/LeveringsBericht/Levering[*]/Ladingdrager[*]/Goederen[*]/Koper[not(kop_gln=$firstBuyer)])” />
  <xsl:if test=”$dbg=1″>
    <xsl:element name=”BuyerInfo”>
      <xsl:element name=”TotalBuyers”>
        <xsl:value-of select=”$buyers” />
      <xsl:element name=”FirstBuyer”>
        <xsl:value-of select=”$firstBuyer” />
      <xsl:element name=”OtherBuyers”>
        <xsl:value-of select=”$otherBuyers” />
  <xsl:if test=”$otherBuyers=0″>
    <xsl:if test=”string-length($firstBuyer) > 0″>
      <xsl:element name=”BuyerParty”>
        <xsl:element name=”PrimaryID”>
          <xsl:value-of select=”$firstBuyer” />
        <xsl:element name=”schemeID”>
          <xsl:value-of select=”$var1″ />
        <xsl:element name=”schemeAgencyName”>
          <xsl:value-of select=”$var2″ />

Comments: 0

Comments are closed.

  • Recent Posts
  • Recent Comments
  • Archives
  • Categories
  • Meta