问题
This is my XML:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="coursestyle.xsl"?>
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<ns0:FindCoursesForOffenderResponse xmlns:ns0="http://H.FindCoursesForOffenderResponse">
<ns0:SiteList>
<ns0:SiteEntity>
<ns0:SiteId>10</ns0:SiteId>
<ns0:SiteName>Ramada Watford</ns0:SiteName>
</ns0:SiteEntity>
<ns0:SiteEntity>
<ns0:SiteId>20</ns0:SiteId>
<ns0:SiteName>Ramada Jarvis (Comet) Hotel</ns0:SiteName>
</ns0:SiteEntity>
</ns0:SiteList>
<ns0:CourseList>
<ns0:CourseEntity>
<ns0:CourseId>50</ns0:CourseId>
<ns0:SiteId>10</ns0:SiteId>
</ns0:CourseEntity>
<ns0:CourseEntity>
<ns0:CourseId>10</ns0:CourseId>
<ns0:SiteId>10</ns0:SiteId>
</ns0:CourseEntity>
<ns0:CourseEntity>
<ns0:CourseId>20</ns0:CourseId>
<ns0:SiteId>20</ns0:SiteId>
</ns0:CourseEntity>
</ns0:CourseList>
</ns0:FindCoursesForOffenderResponse>
</s:Body>
</s:Envelope>
I want to select the SiteName
for each CourseEntity
. For example for the CourseID = 50
the SiteName
should be Ramada Watford
.
So far I have this XSL but it doesn't work.
<?xml version='1.0'?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ns0="http://H.FindCoursesForOffenderResponse" xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<xsl:output method="html"/>
<xsl:param name="lnum">123</xsl:param>
<xsl:template match="/">
<html>
<body>
<ul>
<xsl:for-each select="s:Envelope/s:Body/ns0:FindCoursesForOffenderResponse/ns0:CourseList/ns0:CourseEntity">
<xsl:variable name="currEntity"><xsl:value-of select="ns0:SiteId"/></xsl:variable>
<xsl:value-of select="$currEntity"/><br/>
<xsl:for-each select="s:Envelope/s:Body/ns0:FindCoursesForOffenderResponse/ns0:SiteList/ns0:SiteEntity[ns0:SiteId=$currEntity]">
<li>
<xsl:value-of select="ns0:SiteName"/>
</li>
</xsl:for-each>
</xsl:for-each>
</ul>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
The first for-each
loop runs through CourseEntities
and the inner loop is trying to find the relevant site name for each course id.
Any idea?
output
<couseID> - <sitename>
50 - Ramada Watford
20 - Ramada Jarvis (Comet) Hotel
回答1:
For-each loops are normally best avoided in XSLT. Try this templated approach.
Runnable demo at this XMLPlayground
<!-- kick things off -->
<xsl:template match="s:Envelope/s:Body/ns0:FindCoursesForOffenderResponse">
<ul>
<xsl:apply-templates select='ns0:CourseList/ns0:CourseEntity' />
</ul>
</xsl:template>
<!-- site entities... -->
<xsl:template match='ns0:CourseEntity'>
<li>
<xsl:value-of select='ns0:CourseId' />
-
<!-- ...find corresponding site name -->
<xsl:value-of select='../../ns0:SiteList/ns0:SiteEntity[ns0:SiteId = current()/ns0:SiteId]/ns0:SiteName' />
</li>
</xsl:template>
来源:https://stackoverflow.com/questions/11827023/xsl-for-each-for-different-nodes-in-xml-file