I am trying to turn the following into a table, but I am having a hard time understanding how it parses through all of the child nodes. Will it go through each element until the last one or do I need to have a for-each for each parent node? Also, if there are multiple occurrences of "capris" allowed, do I need to have cells for each possible occurrence (say if there are 3 max but I only have 2, then I would still need 3 cells displayed).
XML:
<Persons xmlns = "">
<Person>
<Shirts>One</Shirts>
<Pants>
<Jeans>
<Shorts>One</Shorts>
<Capris>One</Capris>
<Capris>Two</Capris>
</Jeans>
<Dress>One</Dress>
</Pants>
</Person>
<Person>
<Shirts>One</Shirts>
<Pants>
<Jeans>
<Shorts>One</Shorts>
<Capris>One</Capris>
<Capris>Two</Capris>
<Capris>Three</Capris>
</Jeans>
<Dress>One</Dress>
</Pants>
</Person>
</Persons>
XSL:
<table border="1">
<tr bgcolor="yellow">
<td><b>Shirts</b></td>
<td><b>Shorts</b></td>
<td><b>Capris</b></td>
<td><b>Capris</b></td>
<td><b>Capris</b></td>
</tr>
<xsl:for-each select="Persons">
<xsl:sort select="Persons/Persib" />
<tr style="font-size: 10pt; font-family: verdana">
<td><xsl:value-of select="Shirts"/></td>
<td><xsl:value-of select="Shorts"/></td>
<td><xsl:value-of select="Capris"/></td>
</tr>
</xsl:for-each>
</table>
You had your xsl:for-each
matching rule wrong.
Use the following template: it matches the root <Persons>
element, creates the <html>
and <body>
elements and the <table>
.
Finally, it iterates over the <Person>
elements with an xsl:for-each
. This works, because the context node is right ( Person
is a child of Persons
).
The Capris
situation is resolved by iterating over all Capris
elements and creating a <td>
for each present element. You can see this by looking at the borders of the elements.
One thing left to be corrected is the xsl:sort
element. It tries to sort by the value of a <Persib>
element which is not present in the example. I guess that you can fix this on your own.
<xsl:template match="/Persons">
<html>
<body>
<table border="1">
<tr bgcolor="yellow">
<td><b>Shirts</b></td>
<td><b>Shorts</b></td>
<td><b>Capris</b></td>
<td><b>Capris</b></td>
<td><b>Capris</b></td>
</tr>
<xsl:for-each select="Person">
<xsl:sort select="Persib" />
<tr style="font-size: 10pt; font-family: verdana">
<td>
<xsl:value-of select="Shirts"/>
</td>
<td>
<xsl:value-of select="Pants/Jeans/Shorts"/>
</td>
<xsl:for-each select="Pants/Jeans/Capris">
<td>
<xsl:value-of select="." />
</td>
</xsl:for-each>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
The output should be as desired.
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.