这里是定义所需的变量,一个紧凑的方式:
<xsl:variable name="vKey1" select=
"(/*/rootcontainer/dictionary/key1
|
/*/dictionary/key1
)
[1]
"/>
<xsl:variable name="vKey2" select=
"(/*/rootcontainer/dictionary/key2
|
/*/dictionary/key2
)
[1]
"/>
当包裹在一个简单的XSLT样式表:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:variable name="vKey1" select=
"(/*/rootcontainer/dictionary/key1
|
/*/dictionary/key1
)
[1]
"/>
<xsl:variable name="vKey2" select=
"(/*/rootcontainer/dictionary/key2
|
/*/dictionary/key2
)
[1]
"/>
<xsl:template match="/">
Key1: <xsl:value-of select="$vKey1"/>
Key2: <xsl:value-of select="$vKey2"/>
</xsl:template>
</xsl:stylesheet>
和施加在提供的XML文档(校正,因为它是严重畸形):
<rootnode>
<rootcontainer>
<dictionary>
<key1> value </key1>
</dictionary>
<pages>
<page1> </page1>
</pages>
</rootcontainer>
<dictionary>
<key1> independent value </key1>
<key2> value 2 </key2>
</dictionary>
</rootnode>
有用,正确的结果产生:
Key1: value
Key2: value 2
说明:
该表达式:
(/*/rootcontainer/dictionary/key1
|
/*/dictionary/key1
)
[1]
装置:
取(可能)的两个要素的节点集,并从中取在文档顺序的第一个。
因为这两个元素中的第二个以文档顺序出现,所以它将成为第一个(也是选定的),仅当围绕联合(|
)运算符的两个XPath表达式中的第一个不选择任何元件。
好问题,+1。请参阅我的答案,了解最紧凑和最优雅的(迄今为止)单个单行XPath解决方案。 :) – 2011-01-27 20:32:17
你的问题不清楚。为了*“把最近的字典值的值赋给给一个[n]节点”*,你需要提供输入样本和上下文节点。 *“在'page1`里面创建变量`$ key1`和`$ key2`”*对我来说没有意义,除非你想说你想输出变量`$ key1`和`$ key`的值到元素`page1`内容模板。 – 2011-01-28 18:16:06