So below you can see my given XML. I matched the template and I'm already in the Student-node ( xsl:template match="Class/Student"
):
<Class>
<Heading>This is a sentence.</Heading>
<Student>Alex</Student>
<Student>Emilia</Student>
<Student>John</Student>
</Class>
Now I need to get a list out of all Students and what I want to get should look like this:
<ul>
<li>Alex</li>
<li>Emilia</li>
<li>John</li>
</ul>
I think I have a mistake in the way I am thinking, because my XSLT looks like this at the moment:
<xsl:template match="Class/Student">
<ul>
<xsl:for-each select="../Student">
<li>
<xsl:apply-templates/>
</li>
</xsl:for-each>
</ul>
</xsl:template>
But what I actually get is:
<ul>
<li>Alex</li>
<li>Emilia</li>
<li>John</li>
<ul>
<ul>
<li>Alex</li>
<li>Emilia</li>
<li>John</li>
<ul>
<ul>
<li>Alex</li>
<li>Emilia</li>
<li>John</li>
<ul>
I think the problem is the for-each I use but I have no idea what else I should do in this case.
You want one ul
per Class
, not per Student
, so change
<xsl:template match="Class/Student">
to
<xsl:template match="Class">
Then change
<xsl:for-each select="../Student">
to
<xsl:for-each select="Student">
to get one li
per Student
child element of the Class
current node.
As you have already made the step to use template matching with the template match="Class/Student"
I would suggest to stick with that approach and simply write two templates, one for the Class
elements, the other for the Student
elements
<xsl:template match="Class">
<ul>
<xsl:apply-templates select="Student"/>
</ul>
</xsl:template>
<xsl:template match="Student">
<li>
<xsl:apply-templates/>
</li>
</xsl:template>
For more complex cases this results in cleaner and more modular code.
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.