考虑以下xml:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<node1></node1>
<attribute1>test</attribute1>
</root>
和这个转变:
<xsl:template match="/root">
<result>
<xsl:for-each select="*[starts-with(local-name(), 'node')]">
---
<xsl:value-of select="concat('attribute', string(position()))"/>
---
<xsl:variable name="attribute" select="../*[local-name() = 'attribute1']"/>
<xsl:value-of select="$attribute"/>
---
<xsl:variable name="test"
select="../*[local-name() = concat('attribute', string(position()))]"/>
<xsl:value-of select="$test"/>
---
<xsl:variable name="test2"
select="../*[local-name() = concat('attribut','e1')]"/>
<xsl:value-of select="$test2"/>
---
</xsl:for-each>
</result>
</xsl:template>
令我惊讶的是,我的变量$test
是空的。我认为这与使用concat
或string
函数有关,但我无法弄清楚是什么原因引起的。
有什么想法吗?非常感谢!
答案 0 :(得分:2)
嗯,节点集attribute1
中../*
节点的位置是2,position()
指的是该位置。所以以下行工作
<xsl:variable name="test" select="../*[local-name() = concat('attribute', string(position()-1))]"/>
<xsl:value-of select="$test"/>
并提供所需的输出。
答案 1 :(得分:2)
请注意,如果将输入更改为:
,测试结果会有何不同<?xml version="1.0" encoding="UTF-8"?>
<root>
<attribute1>test</attribute1>
<node1></node1>
</root>
为什么?因为position()
函数放在谓词中时,会返回被过滤的节点的位置(在您的示例中为../*
),而不是当前的位置节点。请在此处查看更详细的说明:http://www.w3.org/TR/xpath/#predicates