条件兄弟值

时间:2011-01-27 19:17:40

标签: xslt xpath

我需要编写一个XSLT来获取给定节点的最近字典值的值。例如,我的结构可以如下所示

<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>

我想在$key1内创建变量$key2page1$key1的值为“value”,$key2的值为“value 2”。如果rootcontainer\dictionary\key1不存在,则$key1的值将为“独立值”。

我希望这是有道理的。

2 个答案:

答案 0 :(得分:2)

以下是定义所需变量的简洁方法:

 <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表达式中的第一个围绕union(|)运算符时才会出现。 t选择任何元素。

答案 1 :(得分:0)

我不确定我是否理解这个问题,但您可以通过两种方式为变量分配条件值:

<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的值将是前一个字典中的<key1>节点(如果有),如果没有,则为<key1>节点。这是对的吗?

(如果您愿意,也可以使用if/then/else结构,但我使用xsl:choose,因为它可能更容易阅读。)