XSLT/XPATH - Find table row with the most columns

2019-08-22 01:43发布

问题:

I'm transforming an xml table to a different table spec, and I need to determine the maximum number of columns that are present in any row in a given table. So if my XML is:

<table>
    <row>
        </column>
    </row>
    <row>
        </column>
        </column>
        </column>
    </row>
    <row>
        </column>
        </column>
    </row>  
</table>

I need to get "3" as a variable in my table template so that I can rewrite the table as follows:

<table cols="3">
...

I'm doing this, which is very dumb (but just good enough...).

    <xsl:template match="table">        
        <xsl:variable name="high_col_count">
            <xsl:choose>
                ...
                <xsl:when test="tr/td[position()=4]">4</xsl:when>
                <xsl:when test="tr/td[position()=3]">3</xsl:when>
                <xsl:when test="tr/td[position()=2]">2</xsl:when>
                ...
            </xsl:choose>
        </xsl:variable>
    ...
</xsl:template>

I can't determine a better was to do this without iterating over a variable, which as I understand isn't possible in xslt due to variables being immutable. Is there an easier way to simply retrieve the count from the row with the most columns?

回答1:

Try using this instead:

<xsl:template match="table">
  <table cols="{max(row/count(column))}">
  ...
  </table>
</xsl:template>


标签: xml xslt xpath