开发者

How can I add multiple filters to a XSLT for-each statement?

I开发者_运维技巧 have the following XSLT node:

<xsl:for-each select="Book[title != 'Moby Dick']">
....
</xsl:for-each>

However, I'd like use multiple filters in the for-each. I've tried the following, but it doesn't seem to work:

<!-- Attempt #1 -->
<xsl:for-each select="Book[title != 'Moby Dick'] or Book[author != 'Rowling'] ">
....
</xsl:for-each>


<!-- Attempt #2 -->
<xsl:for-each select="Book[title != 'Moby Dick' or author != 'Rowling']">
....
</xsl:for-each>


However, I'd like use multiple filters in the for-each

Your real question is an XPath one: Is it possible, and how, to specify more than one condition inside a predicate?

Answer:

Yes, use the standard XPath boolean operators or and and and the standard XPath function not().

In this particular case, the XPath in the select attribute may be:

Book[title != 'Moby Dick' or author != 'Rowling']

I personally would always prefer to write an equivalent expression:

Book[not(title = 'Moby Dick') or not(author = 'Rowling')]

because the != operator has a non-intuitive behavior when one of its operands is a node-set.

But I am guessing that what you probably wanted was to and the two comparissons -- not to or them.


Apparently, I forgot to refresh my data. Attempt #2 works perfectly fine. Hopefully this example helps someone else.

<!-- Attempt #2 -->
<xsl:for-each select="Book[title != 'Moby Dick' or author != 'Rowling']">
....
</xsl:for-each>


If you want multiple predicates, the simplest way is just to use multiple predicates. I'm guessing you really want an "and" rather than an "or":

<xsl:for-each select="Book[title != 'Moby Dick'][author != 'Rowling'] ">
....
</xsl:for-each>

Generally the != operator is best avoided, because it has unexpected effects when the author is absent or when there are multiple authors. It's better to write:

<xsl:for-each select="Book[not(title = 'Moby Dick')][not(author = 'Rowling')] ">
....
</xsl:for-each>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜