[xsl] iterate through nodes and determine output by node type

Subject: [xsl] iterate through nodes and determine output by node type
From: Mario Madunic <hajduk@xxxxxxxx>
Date: Mon, 1 Oct 2007 08:40:51 -0700
I'd like to test all child elements of a body tag and wrap any text nodes (that
can contain child elements itself)in a p tag and <apply-templates /> to any
element nodes.

Using XSLT 1.1

Sample input

<body>
  blah blah blah <strong>blah blah blah</strong>
  <p>a paragraph...</p>
  <p>a paragraph...</p>
  <table>
    <tr>
      <td>content goes here</td>
      <td>content goes here</td>
    <tr>
  </table>
</body>

sample output

<body>
  <p>blah blah blah <strong>blah blah blah</strong></p>
  <p>a paragraph...</p>
  <p>a paragraph...</p>
  <table>
    <tr>
      <td>content goes here</td>
      <td>content goes here</td>
    <tr>
  </table>
</body>

Sample code

<xsl:template match="//body">
  <body>
    <xsl:for-each select="child::*">
      <xsl:choose>
        <xsl:when test="text()">
          <p id="{generate-id()}"><xsl:apply-templates /></p>
        </xsl:when>
        <xsl:otherwise>
          <xsl:apply-templates />
        </xsl:otherwise>
      </xsl:choose>					
    </xsl:for-each>
  </body>
</xsl:template>

Thanks

Marijan (Mario) Madunic

Current Thread