简体   繁体   中英

XSLT — Counting attributes within an element

I have XML similar to

<BOXHEAD>
  <COLHEAD H="1">Item</COLHEAD>
  <COLHEAD H="2">Cost</COLHEAD>
  <COLHEAD H="3">Direct</COLHEAD>
  <COLHEAD H="3">In-Direct</COLHEAD>
  <COLHEAD H="2">Revenue</COLHEAD>
  <COLHEAD H="3">1989</COLHEAD>
  <COLHEAD H="3">1990</COLHEAD>
</BOXHEAD>

I have tried something similar to this to translate to an HTML COLSPAN:

<xsl:if test="@H=2">
    <xsl:variable name="descendants" select="following-sibling::COLHEAD[@H = 3]"/>
    <xsl:variable name="number_of_columns_under_this" select="count($descendants)"/>
    <xsl:if test="$number_of_columns_under_this &gt; 1">
        <xsl:attribute name="colspan">
            <xsl:value-of select="$number_of_columns_under_this"/>
        </xsl:attribute>
    </xsl:if>
</xsl:if>

Desired result: "cost" column should come out to colspan="2" but of course the count() picks up all four of the @H="3" in the block. I'm trying to turn that ancient SGML into an HTML table. The desired out put is similar to this:

<table>
<tbody>
<tr>
    <td colspan="1" rowspan="2">Item</td>
    <td colspan="2" rowspan="1">Cost</td>
    <td colspan="2" rowspan="1">Revenue</td>
</tr>
<tr>
    <td>Direct</td>
    <td>In-Direct</td>
    <td>1989</td>
    <td>1990</td>
</tr>
</tbody>
</table>

Calculating the rowspan and colspan is proving to be difficult for me.

You can use a trick like this

<xsl:variable name="descendants"
    select="following-sibling::COLHEAD[@H = 3]
       [generate-id((preceding-sibling::COLHEAD[@H=2])[last()])
         = generate-id(current())]"/>

This selects all COLHEAD[@H=3] elements whose nearest preceding-sibling @H=2 is the one we're currently looking at.

如果您使用的是XSLT 2.0,则可能应该为此使用位置分组,例如<xsl:for-each-group group-starting-with="[@H='2']> 。但不知道确切的输出结果想要,很难为您提供更多细节。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM