问题
I am currently working with XSLT and trying to group nodes by a sub-string of an attribute. The only thing is I'm working in an environment where I can't use an xsl:key. I was wondering the best way to go about grouping something such as:
<RESULTS>
<RESULT ID="Result:1-1" Value="32" />
<RESULT ID="Result:1-2" Value="3225" />
<RESULT ID="Result:1-3" Value="372" />
<RESULT ID="Result:1-4" Value="64732" />
<RESULT ID="Test:2-1" Value="6362" />
<RESULT ID="Test:2-2" Value="352" />
<RESULT ID="Test:2-3" Value="325" />
<RESULT ID="Result:3-1" Value="3243" />
<RESULT ID="Result:3-2" Value="2332" />
<RESULT ID="Result:3-3" Value="342" />
<RESULT ID="Result:3-4" Value="2134" />
</RESULTS>
So that it could be formatted where there is a table that groups the Results by the last digit in the ID and displays their values. For example, it would group Result:1-1, Test:2-1, and Result:3-1 in the first table and list their values below it.
Some sort of expected result would be:
| Table 1 |
|---------|
| 32 |
| 6362 |
| 3243 |
| Table 2 |
|---------|
| 3225 |
| 352 |
| 2332 |
| Table 3 |
|---------|
| 372 |
| 325 |
| 342 |
| Table 4 |
|---------|
| 64732 |
| 2134 |
Any suggestions as to certain methods of grouping to use or certain fuctions would be much appreciated! Thanks for reading and any help you have to offer!
回答1:
The alternative to Muenchian grouping is described in the same article that explains it; it is also labeled there as "very inefficient".
The following stylesheet:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="/RESULTS">
<html>
<xsl:for-each select="RESULT">
<xsl:variable name="key" select="substring(@ID, string-length(@ID))" />
<xsl:if test="not(preceding-sibling::RESULT[substring(@ID, string-length(@ID))=$key])">
<table border="1">
<tr>
<th>
<xsl:text>Table </xsl:text>
<xsl:value-of select="$key"/>
</th>
</tr>
<xsl:for-each select="../RESULT[substring(@ID, string-length(@ID))=$key]">
<tr>
<td>
<xsl:value-of select="@Value"/>
</td>
</tr>
</xsl:for-each>
</table>
</xsl:if>
</xsl:for-each>
</html>
</xsl:template>
</xsl:stylesheet>
when applied to your example input, will return (rendered):
Note that this is different from the result you have posted - but I believe it is correct nevertheless.
来源:https://stackoverflow.com/questions/38086580/how-to-do-a-for-each-group-in-xslt-1-0-without-keys-muenchian-grouping