1

I've a XML structure like:

<TOP>top</TOP>
<HDR>header</HDR>
<LINE>line1</LINE>
<LINE>line2</LINE>
<LINE>line3</LINE>
<HDR>header</HDR>
<LINE>line4</LINE>
<LINE>line5</LINE>
<LINE>line6</LINE>

And I want a XLST script to transfer it to:

<TOP>top</TOP>
<HDR>
header
<LINE>line1</LINE>
<LINE>line2</LINE>
<LINE>line3</LINE>
</HDR>
<HDR>
header
<LINE>line4</LINE>
<LINE>line5</LINE>
<LINE>line6</LINE>
</HDR>

Thus: The <HDR>-tag around the LINES until next <HDR>-tag

Can someone help me, please to give me a xslt-script.

eric
  • 61
  • 1
  • 2
  • There are some similarly question (with answers) e.g. [Kayessian method](http://stackoverflow.com/a/3836240/2115381) or http://stackoverflow.com/questions/16188341/create-an-hierarchical-xml-form-an-flat-xml-a-like-book-description – hr_117 May 15 '13 at 17:27

1 Answers1

1

This transformation:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:key name="kFollowing" match="LINE"
          use="generate-id(preceding-sibling::HDR[1])"/>

 <xsl:template match="/*">
   <xsl:copy-of select="TOP"/>
   <xsl:apply-templates select="HDR"/>
 </xsl:template>

 <xsl:template match="HDR">
  <HDR>
    <xsl:copy-of select="key('kFollowing', generate-id())"/>
  </HDR>
 </xsl:template>
</xsl:stylesheet>

when applied on the following XML document (the provided fragment, wrapped into a single top element):

<t>
    <TOP>top</TOP>
    <HDR>header</HDR>
    <LINE>line1</LINE>
    <LINE>line2</LINE>
    <LINE>line3</LINE>
    <HDR>header</HDR>
    <LINE>line4</LINE>
    <LINE>line5</LINE>
    <LINE>line6</LINE>
</t>

produces the wanted, correct result:

<TOP>top</TOP>
<HDR>
   <LINE>line1</LINE>
   <LINE>line2</LINE>
   <LINE>line3</LINE>
</HDR>
<HDR>
   <LINE>line4</LINE>
   <LINE>line5</LINE>
   <LINE>line6</LINE>
</HDR>
Dimitre Novatchev
  • 240,661
  • 26
  • 293
  • 431