xml是
<XYZ>
<manager>
<mId>m1</mId>
<mName>mName1</mName>
<manager>
<manager>
<mId>m2</mId>
<mName>mName2</mName>
<manager>
<department>
<dName>d1</dName>
<dManager>m1</dManager>
<department>
<department>
<dName>d2</dName>
<dManager>m1</dManager>
<department>
<department>
<dName>d3</dName>
<dManager>m2</dManager>
<department>
</XYZ>
对于每个经理,输出他管理的所有部门名称,我的代码就像
<xsl:for-each select="XYZ/manager">
<xsl:variable name='mId'>
<xsl:value-of select="mId"/>
</xsl:variable>
<p>
manager <xsl:value-of select="mName"/> manages department
<xsl:for-each select="XYZ/department[dManager=$mId]">
<xsl:value-of select="XYZ/department/dName"/>,
</xsl:for-each>
</p>
</xsl:for-each>
并且在manages department
之后没有输出任何内容,任何人都知道什么是错的?谢谢!
答案 0 :(得分:4)
您的for-each
内部存在上下文问题:for-each
指令更改了上下文,然后当您应用第二个for-each
时和/或当您调用department/dName
时1}},你不是在正确的背景下。
然后修复你最后的两个选择如下:
<xsl:for-each select="XYZ/manager">
<xsl:variable name='mId'>
<xsl:value-of select="mId"/>
</xsl:variable>
<p>
manager <xsl:value-of select="mName"/> manages department
<xsl:for-each select="/XYZ/department[dManager=$mId]">
<xsl:value-of select="dName"/>,
</xsl:for-each>
</p>
</xsl:for-each>
答案 1 :(得分:2)
这可能会对你有所帮助。修改了你的XPath,只需对输出格式进行少许修改:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" indent="yes" />
<xsl:strip-space elements="*"/>
<xsl:template match="/">
<xsl:for-each select="/XYZ/manager">
<xsl:variable name='mId'>
<xsl:value-of select="mId"/>
</xsl:variable>manager <xsl:value-of select="mName"/> manages department <xsl:for-each select="/XYZ/department[dManager=$mId]">
<xsl:value-of select="dName"/>
<xsl:if test="position() != last()">, </xsl:if>
</xsl:for-each>
<xsl:if test="position() != last()">
<xsl:text>
</xsl:text>
</xsl:if>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>