1

Need to convert HTML table to XML. In HTML we have table header like that

<table>
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    <td colspan="2">45</td>
    <td>6</td>
    <td>7</td>
  </tr>
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    <td>4</td>
    <td>5</td>
    <td>6</td>
    <td>7</td>
  </tr>
<table/>
In XML result must be counter throw all elments considering rowspan attribute value.

<zr>
  <zc r="1" l="1">
    <zl>1</zl>
  </zc>
  <zc r="2" l="1">
    <zl>2</zl>
  </zc>
  <zc r="3" l="1">
    <zl>3</zl>
  </zc>
  <zc r="4" l="2">
    <zl>45</zl>
  </zc>
  <zc r="6" l="1">
    <zl>6</zl>
  </zc>
  <zc r="7" l="1">
    <zl>7</zl>
  </zc>
</zr>
<zr>
  <zc r="1" l="1">
    <zl>1</zl>
  </zc>
  <zc r="2" l="1">
    <zl>2</zl>
  </zc>
  <zc r="3" l="1">
    <zl>3</zl>
  </zc>
  <zc r="4" l="1">
    <zl>4</zl>
  </zc>
  <zc r="5" l="1">
    <zl>5</zl>
  </zc>
  <zc r="6" l="1">
    <zl>6</zl>
  </zc>
  <zc r="7" l="1">
    <zl>7</zl>
  </zc>
</zr>

In XMLT I don't know how to set/get variables in loop. Is this possible? XMLT 1.0

1 Answer 1

1

No, it's not possible, because XSLT is a functional language. It doesn't have mutable variables and it doesn't have loops. (xsl:for-each is not a loop, it is a mapping expression, which applies the same operation to every item in a sequence, conceptually in parallel rather than sequentially).

The way to solve your problem (as is often the case in functional languages) is with recursion: specifically, a technique I call "sibling recursion".

From the tr element, process the first td child:

<xsl:template match="tr">
 <xsl:apply-templates select="td[1]" mode="sib">
  <xsl:with-param name="col" select="1"/>
 </xsl:apply-templates>
</xsl:template>

From the td element, process the next sibling td child:

<xsl:template match="td" mode="sib">
 <xsl:param name="col"/>
 <zc col="$col"/>
 <xsl:apply-templates select="following-sibling::td[1]" mode="sib">
  <xsl:with-param name="col">
    <xsl:choose>
      <xsl:when test="@colspan">
        <xsl:value-of select="$col + @colspan"/>
      </xsl:when>
      <xsl:otherwise>
        <xsl:value-of select="$col + 1"/>
      </xsl:otherwise>
    </xsl:choose>
   </xsl:with-param>
 </xsl:apply-templates>
</xsl:template>

(It's much less verbose with XSLT 2.0!)

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

Comments

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.