0

I have the following xml fragment:

<headline>Head1</headline>
<text>Text1</text>
<image>Dummy</image>
<headline>Head2</headline>
<text>Text2</text>
<preview>Abc</preview>

This fragment should be transformed to:

<paragraph>
  <headline>Head1</headline>
  <text>Text1</text>
  <image>Dummy</image>
</paragraph>
<paragraph>
  <headline>Head2</headline>
  <text>Text2</text>
  <preview>Abc</preview>
</paragraph>

So all tags between two headline-tags should be merged into one paragraph-tag.

Could please anybody give me a hint. I have no clue how something like that can be done using XSL.

Werzi2001
  • 2,035
  • 1
  • 18
  • 41

1 Answers1

1

With xslt-1.0 you my try something like this (adaption off https://stackoverflow.com/a/16577804/2115381):

<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="kfHeadline" match="*[local-name() != 'headline']"
         use="generate-id(preceding-sibling::headline[1])"/>

    <xsl:template match="/*">
        <out>
        <xsl:apply-templates select="headline"/>
        </out>
    </xsl:template>

    <xsl:template match="headline">
        <paragraph>
            <xsl:copy-of select="."/>
            <xsl:copy-of select="key('kfHeadline', generate-id())"/>
        </paragraph>
    </xsl:template>
</xsl:stylesheet>

Which will generate the following output:

<out>
  <paragraph>
    <headline>Head1</headline>
    <text>Text1</text>
    <image>Dummy</image>
    <headline>Head2</headline>
  </paragraph>
  <paragraph>
    <headline>Head2</headline>
    <text>Text2</text>
    <preview>Abc</preview>
  </paragraph>
</out>
Community
  • 1
  • 1
hr_117
  • 9,589
  • 1
  • 18
  • 23
  • i think there must be a further condition to exclude the following headline-tag from the group (in your example "Head2" is also added to the first group). i'll check that. – Werzi2001 Jun 25 '13 at 07:42
  • Oh sorry. You can change the xsl:key (have a look to the update). – hr_117 Jun 25 '13 at 09:12