Jan Jan - 1 month ago 16
HTML Question

Dynamic HTML Table with XSLT

I need to loop over a group of values and print them into a two-column table.

I thought about following solution (must be xslt1)

<table class="main">

<xsl:for-each select="Attribute/Gruppe">
<xsl:if test="current()/@ID=20064490">
<xsl:variable name="open_row"><![CDATA[<tr><td style="width:50%;">
<xsl:value-of select="current()/@name" /></td>]]></xsl:variable>
<xsl:variable name="closing_row"><![CDATA[<td style="width:50%;">
<xsl:value-of select="current()/@name" /></td></tr>]]></xsl:variable>

<xsl:variable name="table">
<xsl:for-each select="*">
<xsl:choose>
<xsl:when test="(position() mod 2) = 1">
<xsl:value-of select="$open_row"
disable-output-escaping="yes" />

</xsl:when>
<xsl:otherwise>

<xsl:value-of select="$closing_row"
disable-output-escaping="yes" />

</xsl:otherwise>
</xsl:choose>
</xsl:for-each>
</xsl:variable>
<xsl:value-of select="$table"
disable-output-escaping="yes" />
</xsl:if>
</xsl:for-each>
</table>


I modified the code now I am using
position()
to find out if an closing
<tr>
or an opening
</tr>
is required.

The whole problem might be summarized to that you can not write single tags in XSLT. And that
disable-output-escaping
is not working.

Resulting HTML should be https://jsfiddle.net/dwetctm6/

For all the Nodes in the group. The order of the nodes in the table does not matter.

Furthermore assume following XML:


<bgroup>
<NODE1>text</NODE1>
<NODE2>text</NODE2>
<NODE n-1>text</NODE n-1>
<NODE n>text</NODE n>
</bgroup>


Answer

Dividing nodes into a two-column table is pretty trivial - especially if the order (across-first or down-first) does not matter.

Consider the following stylesheet:

XSLT 1.0

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

<xsl:template match="/bgroup">
    <table border="1">
        <xsl:for-each select="*[position() mod 2 = 1]">
            <tr>
                <td><xsl:value-of select="."/></td>
                <td><xsl:value-of select="following-sibling::*[1]"/></td>
            </tr>
        </xsl:for-each>
    </table>
</xsl:template>

</xsl:stylesheet>

Applied to the following well-formed inpout:

XML

<bgroup>
  <NODE1>A</NODE1>
  <NODE2>B</NODE2>
  <NODE3>C</NODE3>
  <NODE4>D</NODE4>
  <NODE5>E</NODE5>
</bgroup>

the result will be:

<table border="1">
   <tr>
      <td>A</td>
      <td>B</td>
   </tr>
   <tr>
      <td>C</td>
      <td>D</td>
   </tr>
   <tr>
      <td>E</td>
      <td/>
   </tr>
</table>

rendered as:

enter image description here

Comments