0

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

3
  • Well, what is the task? To wrap all adjacent tr elements into a table element? Which version of XSLT, which XSLT processor do you use/can you use? Commented Oct 13, 2018 at 9:59
  • Hi @Martin, sorry for missing info Commented Oct 13, 2018 at 10:03
  • Do you know that those div class="group-body" elements do always contain only tr elements that need to be wrapped by a table parent? Commented Oct 13, 2018 at 10:06

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Hi Martin, need some minor help, how about in this scenario? xsltfiddle.liberty-development.net/94hvTzX/8 additional conditions needed? Sorry for inconveniences
Hi Martin, I have solved it, will ask another for the perfect solution for XSLT, because currently, I have used 2 templates to complete the conversion process. By the way, thanks and happy weekend !

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.