Xslt 条件同级值
我需要编写一个XSLT来获取与给定节点最近的字典值的值。例如,我的结构可以如下所示Xslt 条件同级值,xslt,xpath,Xslt,Xpath,我需要编写一个XSLT来获取与给定节点最近的字典值的值。例如,我的结构可以如下所示 <rootnode> <rootcontainer> <dictionary> <key1> value /<key1> </dictionary> <pages> <page1> <!--xslt goes here--> </page1> &l
<rootnode>
<rootcontainer>
<dictionary>
<key1> value /<key1>
</dictionary>
<pages>
<page1>
<!--xslt goes here-->
</page1>
</pages>
</rootcontainer>
<dictionary>
<key1>
independent value
</key1>
<key2>
value 2
</key2>
</dictionary>
</rootnode>
价值观/
独立值
价值2
我想在page1
中创建变量$key1
和$key2
。$key1
的值将是“值”,而$key2
的值将是“值2”。如果rootcontainer\dictionary\key1
不存在,$key1
的值将是“独立值”
我希望这是有道理的 我不确定我是否理解这个问题,但您可以通过两种方式为变量指定条件值:
<xsl:choose>
<xsl:when test="your test condition">
<xsl:variable name="key1" select="your value">
</xsl:when>
<xsl:otherwise>
<xsl:variable name="key1" select="your alternative value">
</xsl:otherwise>
</xsl:choose>
或者更简洁地说:
<xsl:variable name="key1" select="if(your test condition) then your value else your alternative value;"/>
更新:感谢您更新问题。我现在就去试一试
<xsl:template match="page1">
<xsl:choose>
<xsl:when test="../../preceding-sibling:dictionary[1]/key1">
<xsl:variable name="key1" select="../../preceding-sibling:dictionary[1]/key1">
</xsl:when>
<xsl:otherwise>
<xsl:variable name="key1" select="../../../following-sibling:dictionary[1]/key1">
</xsl:otherwise>
</xsl:choose>
</xsl:template>
因此,$key1
的值将是前一个字典中的
节点(如果有),而下一个字典中的
节点(如果没有)。对吗
(如果您愿意,也可以使用
if/then/else
结构,但我使用了xsl:choose
,因为它可能更容易阅读。)这里有一种简洁的方法来定义所需的变量:
<xsl:variable name="vKey1" select=
"(/*/rootcontainer/dictionary/key1
|
/*/dictionary/key1
)
[1]
"/>
<xsl:variable name="vKey2" select=
"(/*/rootcontainer/dictionary/key2
|
/*/dictionary/key2
)
[1]
"/>
<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>
说明:
Key1: value
Key2: value 2
表达方式:
(/*/rootcontainer/dictionary/key1
|
/*/dictionary/key1
)
[1]
表示:
获取两个元素(可能)的节点集,并从中获取文档顺序中的第一个元素
因为,这两个元素中的第二个按文档顺序排在后面,只有当union(
|
)运算符周围的两个XPath表达式中的第一个没有选择任何元素时,它才会是第一个(并被选中)。Hi Biziclop..感谢您的回复…我更新了帖子以展示我的xml结构。希望这能增加一点清晰度。我的问题是,这个key1中变量的名称应该取自dictionary下节点的名称,select值应该是与相关节点最近的key1值……@Technocrat Aspire不,我仍然不明白。你想让下一个元素具有相同的元素名吗?每个key1
变量分别在xsl:when
和xsl:others
之间,但是xsl:choose
@Alejandro之外没有人是这样的,但我当时不太明白OP想要什么。问得好,+1。请参阅我的答案,以了解(迄今为止)最紧凑、最精巧的单行XPath解决方案。:)你的问题不清楚。为了“获取给定[n]节点的最近字典值的值”,您需要提供输入示例和上下文节点。“在page1
中创建变量$key1
和$key2
”对我来说没有任何意义,除非您试图说希望将变量$key1
和$key
的值输出到元素page1
内容模板中。
(/*/rootcontainer/dictionary/key1
|
/*/dictionary/key1
)
[1]