3

这是条目25317199中问题的续集。

在 25317199 帖子中,数据有 2 个块,即SchoolsFamilySmithFamilySmith中的数据用作检索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>&#xa;</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() 来识别“来自谓词之外的当前上下文节点”。但似乎问题出在其他地方。请指教。非常感谢。

4

1 回答 1

3

问题是绝对路径以/解析相对于包含当前上下文节点的树的根节点开始,这不一定是输入 XML 文档。里面

<xsl:for-each select="exsl:node-set($FamilySmith)/Children/Child">

该路径/Doc/Schools正在查找Doc派生自的临时文档中的元素$FamilySmith(因此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>&#xa;</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>
于 2014-08-17T15:47:34.800 回答