即使不完全清楚您的期望,我也会尝试回答。
据我了解,您希望找到与 <d>
元素具有相同位置的<e>
元素。
这可以通过将当前位置作为变量来实现。
xsl:variable name ="pos" select="position()" />
<xsl:value-of select="//b/d[position() = $pos]/@id" />
或使用计数preceding-sibling
<xsl:value-of select="//b/d[(count(current()/preceding-sibling::*)+1)]/@id" />
更新下面的部分是因为“所有行业的乔治”的评论而改变的。
请注意,结果position()
取决于调用上下文。
例如下面的测试 xslt(版本 1.0):
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/">
<Lessons>
<!-- Wrong result with position -->
<xsl:for-each select="//c/e">
<xsl:call-template name="lesson" />
</xsl:for-each>
</Lessons>
<Lessons2>
<!-- Wonted result even with position -->
<xsl:for-each select="//c">
<xsl:for-each select="e">
<xsl:call-template name="lesson" />
</xsl:for-each>
</xsl:for-each>
</Lessons2>
</xsl:template>
<xsl:template name="lesson">
<Lesson>
<Teacher>
<xsl:value-of select="@id" />
<xsl:text>,</xsl:text>
<xsl:value-of select="count(./preceding-sibling::*)+1" />
<xsl:text>,</xsl:text>
<xsl:variable name ="pos" select="position()" />
<xsl:value-of select="$pos" />
<xsl:text>,</xsl:text>
<xsl:value-of select="//b/d[position() = $pos]/@id" />
<xsl:text>,</xsl:text>
<xsl:value-of select="//b/d[count(current()/preceding-sibling::*)+1]/@id" />
</Teacher>
</Lesson>
</xsl:template>
</xsl:stylesheet>
使用此输入:
<?xml version="1.0" encoding="utf-16"?>
<xml>
<a>
<b>
<d id="d1"/>
<d id="d2"/>
<d id="d3"/>
</b>
<c>
<e id="e1"/>
<e id="e2"/>
<e id="e3"/>
</c>
<c>
<e id="e21"/>
<e id="e22"/>
<e id="e23"/>
</c>
<c>
<e id="e21"/>
<e id="e22"/>
<e id="e23"/>
</c>
</a>
</xml>
生成此输出:
<Lessons>
<Lesson>
<Teacher>e1,1,1,d1,d1</Teacher>
</Lesson>
<Lesson>
<Teacher>e2,2,2,d2,d2</Teacher>
</Lesson>
<Lesson>
<Teacher>e3,3,3,d3,d3</Teacher>
</Lesson>
<Lesson>
<Teacher>e21,1,4,,d1</Teacher>
</Lesson>
<Lesson>
<Teacher>e22,2,5,,d2</Teacher>
</Lesson>
<Lesson>
<Teacher>e23,3,6,,d3</Teacher>
</Lesson>
<Lesson>
<Teacher>e21,1,7,,d1</Teacher>
</Lesson>
<Lesson>
<Teacher>e22,2,8,,d2</Teacher>
</Lesson>
<Lesson>
<Teacher>e23,3,9,,d3</Teacher>
</Lesson>
</Lessons><Lessons2>
<Lesson>
<Teacher>e1,1,1,d1,d1</Teacher>
</Lesson>
<Lesson>
<Teacher>e2,2,2,d2,d2</Teacher>
</Lesson>
<Lesson>
<Teacher>e3,3,3,d3,d3</Teacher>
</Lesson>
<Lesson>
<Teacher>e21,1,1,d1,d1</Teacher>
</Lesson>
<Lesson>
<Teacher>e22,2,2,d2,d2</Teacher>
</Lesson>
<Lesson>
<Teacher>e23,3,3,d3,d3</Teacher>
</Lesson>
<Lesson>
<Teacher>e21,1,1,d1,d1</Teacher>
</Lesson>
<Lesson>
<Teacher>e22,2,2,d2,d2</Teacher>
</Lesson>
<Lesson>
<Teacher>e23,3,3,d3,d3</Teacher>
</Lesson>
</Lessons2>