这是条目25317199中问题的后续。
在25317199篇文章中,数据有2个块,即Schools和FamilySmith。FamilySmith中的数据用作检索Schools中的数据的键。
现在,在本例中,数据被分割为FamilySmith现在被定义为样式表中的变量,如下所示:<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:exsl="http://exslt.org/common"
extension-element-prefixes="exsl"
version="1.0">
<xsl:variable name="FamilySmith">
<Children>
<Child>
<Name>Thomas</Name>
<School_Id>5489</School_Id>
</Child>
<Child>
<Name>Andrew</Name>
<School_Id>7766</School_Id>
</Child>
</Children>
</xsl:variable>
<xsl:template match="/Doc">
<xsl:for-each select="exsl:node-set($FamilySmith)/Children/Child">
<xsl:text>
</xsl:text>
<xsl:value-of select="Name"/>
<xsl:text> goes to (school's name here) </xsl:text>
<xsl:value-of select="/Doc/Schools/School[Id = current()/School_Id]/Name"/>
<xsl:text> at (school's address here) </xsl:text>
<xsl:value-of select="/Doc/Schools/School[Id = current()/School_Id]/Address"/>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
这适用于下面的XML数据:
<Doc>
<Schools>
<School>
<Id>5489</Id>
<Name>St Thomas</Name>
<Address>High Street, London, England</Address>
</School>
<School>
<Id>7766</Id>
<Name>Anderson Boys School</Name>
<Address>Haymarket, Edinborough</Address>
</School>
</Schools>
</Doc>
检索学校名称和学校地址都会产生空字符串,如下所示。
Thomas goes to (school's name here) at (school's address here)
Andrew goes to (school's name here) at (school's address here)
我使用了之前的帖子25317199中给出的建议,即使用current()来识别"来自谓词外部的当前上下文节点"。但问题似乎出在其他地方。请建议。多谢。
问题是,以/
开头的绝对路径相对于包含当前上下文节点的树的根节点进行解析,而根节点不一定是输入XML文档。在
<xsl:for-each select="exsl:node-set($FamilySmith)/Children/Child">
路径/Doc/Schools
正在查找从$FamilySmith
派生的临时文档中的Doc
元素(因此value-of
指令不选择任何内容)。您需要在另一个变量
for-each
外部的上下文节点:<xsl:template match="/Doc">
<xsl:variable name="doc" select="." />
<xsl:for-each select="exsl:node-set($FamilySmith)/Children/Child">
<xsl:text>
</xsl:text>
<xsl:value-of select="Name"/>
<xsl:text> goes to (school's name here) </xsl:text>
<xsl:value-of select="$doc/Schools/School[Id = current()/School_Id]/Name"/>
<xsl:text> at (school's address here) </xsl:text>
<xsl:value-of select="$doc/Schools/School[Id = current()/School_Id]/Address"/>
</xsl:for-each>
</xsl:template>