0

is there any way to nest the headings with xlst, like I did it manually in this example? I need to nest the headings h1 up to h3 and change each of them into the tag topic/title.

Old source code

<title>Text Title</title>
<h1>Text H1</h1>
<p>Text</p>
<h2>Text H2</h2>
<p>Text</p>
<h3>Text H3</h3>
<p>Text</p>
<h3>Text H3</h3>
<p>Text</p>
<h3>Text H3</h3>
<p>Text</p>
<h2>Text H2</h2>
<p>Text</p>

Nested new code

<topic>
  <title>Text Title</title>
  <topic>
    <title>Text H1</title>
    <p>Text</p>
    <topic>
      <title>Text H2</title>
      <p>Text</p>
      <topic>
        <title>Text H3</title>
        <p>Text</p>
      </topic>
      <topic>
        <title>Text H3</title>
        <p>Text</p>
      </topic>
      <topic>
        <title>Text H3</title>
        <p>Text</p>
      </topic>
    </topic>
    <topic>
      <title>Text H2</title>
      <p>Text</p>
    </topic>
  </topic>
</topic>

Thanks a lot

3

1 Answer 1

0

Try this XSLT

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="xml" indent="yes" />

    <xsl:key name="group" 
             match="*[starts-with(local-name(), 'h')]" 
             use="generate-id(preceding-sibling::*[local-name() = concat('h', number(substring-after(local-name(current()), 'h')) - 1)])" />

    <xsl:template match="body">
      <topic>
        <xsl:apply-templates select="title|h1" />
      </topic>
    </xsl:template>

    <xsl:template match="*[starts-with(local-name(), 'h')]">
        <topic>
            <title><xsl:value-of select="." /></title>
            <xsl:apply-templates select="following-sibling::p[1]" />
            <xsl:apply-templates select="key('group', generate-id())" />
        </topic>
    </xsl:template>    

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

This defines a key, called group, to group elements starting with h by their first preceding sibling that are an h element of the next number down. So, when you are positioned on a h element, you then use the key to get the nest elements.

Note this also assumes each h element is always followed by one, and only one, p element.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.