0
votes

I've got the below XML document that I'd like to transform using XSLT.

Input:

<ABS>
  <B>Heading 1</B> 
  text
  <B>Heading 2</B> 
  text
  <B>Heading 3</B> 
  text
  <B>Heading 4</B> 
  text
</ABS>

I need to write a transformation so that each heading and it's following text is wrapped in a <sec> tag like the below example shows.

Desired Output:

<ABS>
  <sec>
    <B>Heading 1</B> 
    text
  </sec>
  <sec>
    <B>Heading 2</B> 
    text
  </sec>
  <sec>
    <B>Heading 3</B> 
    text
  </sec>
  <sec>
    <B>Heading 4</B> 
    text
  </sec>    
</ABS>

Does anybody know how I could do this using an XSLT Stylesheet?

Thanks

3

3 Answers

1
votes

Please find the XSLT below:

<?xml version='1.0'?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="ABS">
<xsl:copy>
    <xsl:for-each select="B">
    <sec><xsl:copy-of select="."/><xsl:value-of select="following-sibling::text()[1]"/></sec>   
    </xsl:for-each>
</xsl:copy>
</xsl:template>    
</xsl:stylesheet>
0
votes

This is your solution:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:output indent="yes"/>
  <xsl:template match="ABS">
    <ABS>
      <xsl:apply-templates/>
    </ABS>
  </xsl:template>

  <xsl:template match="*">
    <xsl:choose>
      <xsl:when test="name()='B'">
        <sec>
          <xsl:copy-of select="."/>
          <xsl:value-of select="following-sibling::text()[1]"/>
        </sec>
      </xsl:when>
      <xsl:otherwise>
        <xsl:copy>
          <xsl:copy-of select="."/>
        </xsl:copy>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

  <xsl:template match="text()"/>
</xsl:stylesheet>
0
votes

Try this:

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

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

    <xsl:template match="B">
        <sec>
            <xsl:copy>
                <xsl:apply-templates />
            </xsl:copy>
            <xsl:value-of select="following-sibling::text()[1]"/>

        </sec>
    </xsl:template>
    <xsl:template match="text()[preceding::*[name()='B']]">

    </xsl:template>
</xsl:stylesheet>

Which will generate the following output:

<?xml version="1.0"?>
<ABS>
    <sec><B>Heading 1</B>
    text
    </sec><sec><B/>
    text
    </sec><sec><B/>
    text
    </sec><sec><B/>
    text
</sec></ABS>