user1219310
user1219310

Reputation: 732

How to partial transform in XSLT

I have done XSLT transformation on the XML and now would like to apply XSLT to alter some of the content.

How to wrap all the tr element in table element? I am was using XSLT 1.0 in C#.

XML

<?xml version="1.0" ?>
<div class="group">
  <div class="group-header">A</div>
  <div class="group-body">
    <div class="group">
      <div class="group-header">B</div>
      <div class="group-body">
        <div class="group">
          <div class="group-header">C</div>
          <div class="group-body">
            <tr>C1</tr>
            <tr>C2</tr>
            <tr>C3</tr>
          </div>
        </div>
        <div class="group">
          <div class="group-header">D</div>
          <div class="group-body">
            <tr>D1</tr>
            <tr>D2</tr>
            <tr>D3</tr>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

Expected Result:

enter image description here

Upvotes: 0

Views: 267

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167696

Simply start with the identity transformation template and then add a template for elements containing tr children to wrap them in a table:

<xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">

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

  <xsl:template match="*[not(self::table) and tr]">
      <xsl:copy>
          <xsl:apply-templates select="@*"/>
          <table>
              <xsl:apply-templates/>
          </table>
      </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

https://xsltfiddle.liberty-development.net/6qVRKwV

Upvotes: 2

Related Questions