XSL Rewrite a straight xml structure to nested xml

2019-06-04 07:43发布

问题:

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.

回答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>