RE: [xsl] Manipulating elements depending on the existence of sub-elements

Subject: RE: [xsl] Manipulating elements depending on the existence of sub-elements
From: Wendell Piez <wapiez@xxxxxxxxxxxxxxxx>
Date: Wed, 12 Mar 2008 12:01:23 -0400
At 11:01 AM 3/12/2008, it was written:
Try something like this:

<xsl:template match="/"
  <xsl:apply-templates select="//UniqueInfo"/>
</xsl:template>

<xsl:template match="UniqueInfo">
  <transaction>
    <xsl:apply-templates
select="../preceding-sibling::transaction[not(UniqueInfo)]/line | ../line"/>
  </transaction>
</xsl:template>

This is nearly there, but won't it break when the second group of transactions appears without a UniqueInfo?


As in

<Transaction which="A">
  <Line>...</Line>
  <Line>...</Line>
</Transaction>
<Transaction which="B">
  <Line>...</Line>
  <Line>...</Line>
</Transaction>
<Transaction which="C">
  <Line>...</Line>
  <Line>...</Line>
  <UniqueInfo>...</UniqueInfo>
</Transaction>
<Transaction which="D">
  <Line>...</Line>
  <Line>...</Line>
</Transaction>
<Transaction which="E">
  <Line>...</Line>
  <Line>...</Line>
  <UniqueInfo>...</UniqueInfo>
</Transaction>

... it would work for Lines belonging to C, but Transaction E would get A and B along with D and E.

To fix this, one could use a key to select all the Lines that belong to any given UniqueInfo:

<xsl:key name="Lines-for-UniqueInfo" match="Line"
use="generate-id((../UniqueInfo | ../following-sibling::*/UniqueInfo)[1])"/>


and then

<xsl:template match="UniqueInfo">
  <transaction>
    <xsl:apply-templates
      select="key('Lines-for-UniqueInfo',generate-id())"/>
  </transaction>
</xsl:template>

... and then position() gives you the number as above.

Alternatively, what I often advise people when handling dirty data: write
two transformations and run them in series (a pipeline). The first one is to
clean up the data, the second is to transform it. One benefit is that when
you fix the data supplier to stop generating dirty data, you can throw out
the first stylesheet. Another benefit is that the clean-up stylesheet will
be reusable when you want to process the dirty data in a different way.

Definitely.


Cheers,
Wendell


====================================================================== Wendell Piez mailto:wapiez@xxxxxxxxxxxxxxxx Mulberry Technologies, Inc. http://www.mulberrytech.com 17 West Jefferson Street Direct Phone: 301/315-9635 Suite 207 Phone: 301/315-9631 Rockville, MD 20850 Fax: 301/315-8285 ---------------------------------------------------------------------- Mulberry Technologies: A Consultancy Specializing in SGML and XML ======================================================================

Current Thread