3

我有以下 xsl

<Root>
    <child>
       <Book name="Title" value="hailey" />
       <Book name="Title" value="After death" />
       <Book name="Price" value="100" />
    </child>
    <child>
       <Book name="Title" value="After death" />
       <Book name="genre" value="fiction" />
    </child>
</Root>

我想遍历“子”节点,如果出现“标题”(至少一次),我想设置一个变量。我在 xslt 中使用以下代码

<xsl:variable name="flag">
        <xsl:for-each select="/Root/Child" >
            <xsl:for-each select="./Book" >
                   <xsl:if test="./@name = 'Title'">
                    <xsl:value-of select="'true'"/>                     
                </xsl:if>
            </xsl:for-each>
        </xsl:for-each>


</xsl:variable>

问题是变量“flag”设置为“truetruetrue”时的值,而我希望它只是“true”。任何帮助表示赞赏

4

4 回答 4

7

No need for iteration or conditional instructions at all. Just use this one-liner:

<xsl:variable name="vYourName" select="boolean(/Root/Child/Book[@name='Title'])"/>

For this particular XML document this can be expressed even shorter:

<xsl:variable name="vYourName" select="boolean(/*/*/*[@name='Title'])"/>

Explanation:

Both definitions define the variable named "vYourName" to be true() exactly when at least one of the Root/Child/Book elements has a Title attribute.

Do note:

  1. By definition the function boolean ($ns) returns true if and only if the nodeset $ns is non-empty.

  2. The string representation of the boolean value true() is the string "true".

Update:

In a comment, the OP asked:

if there is atleast one occurence, is there a way to assign the "value" of that to the variable?

The answer: Yes, if by "the value" you mean the first value attribute, use:

 <xsl:variable name="vYourName" select="(/*/*/*[@name='Title'])[1]/@value"/>
于 2012-06-18T11:59:04.170 回答
0
<xsl:variable name="flag">
   <xsl:if test="/Root/Child/Book/@name = 'Title'">
      <xsl:value-of select="'true'"/>                     
   </xsl:if>
</xsl:variable>
于 2012-06-18T11:51:05.390 回答
0

如果您喜欢坚持使用您的代码,可以使用

<xsl:variable name="flag">
    <xsl:for-each select="//Book" >
        <xsl:if test="@name = 'Title'">
            <xsl:value-of select="'true'"/>
        </xsl:if>
    </xsl:for-each>
</xsl:variable>
于 2012-06-18T11:54:50.490 回答
0

未经测试(并且由于 Lucero 的评论而更新)...

<xsl:variable name="flag">
  <xsl:if test="count(/Root/Child/Book[@name='Title'])>0">true</xsl:if>
</xsl:variable>
于 2012-06-18T11:50:27.823 回答