XPath - 测试至少一个节点是否具有给定的值

3

给定以下XML:

<catalog>
    <cd>
        <title>Empire Burlesque</title>
        <artist>Bob Dylan</artist>
        <country>USA</country>
        <company>Columbia</company>
        <price>10.90</price>
        <year>1985</year>
    </cd>
    <cd>
        <title>Greatest Hits</title>
        <artist>Dolly Parton</artist>
        <country>USA</country>
        <company>RCA</company>
        <price>9.90</price>
        <year>1982</year>
    </cd>
    <cd>
        <title>Still got the blues</title>
        <artist>Gary Moore</artist>
        <country>UK</country>
        <company>Virgin records</company>
        <price>10.20</price>
        <year>1990</year>
    </cd>
</catalog>

我想检查至少一个节点是否具有例如“1982年”的年份。类似于:
<xsl:if test="........" ><p>passed!</p></xsl:if>
3个回答

5
在XPath 1.0和XPath 2.0中都是如此:
'1982' = /catalog/cd/year

变体:

XPath 1.0:

1982 = /catalog/cd/year

XPath 2.0:
1982 = /catalog/cd/year/number()

XPath中的=运算符在至少有一个参数为节点集(或XPath 2.0中的序列)时非常强大。当节点集(序列)中至少有一个节点的(原子化)值等于=的另一个参数时,结果为真。这正是这个问题所问的。


1

尝试使用test="index-of(/catalog/cd/year, 1982)"。


谢谢,我也用以下代码得到了相同的结果:test="catalog/cd/year[contains(.,'1982')]" - Wojciech Owczarczyk
1
@VoodooRider:contains()不是你想要的--你想要测试相等性。 - Dimitre Novatchev

0

这样怎么样:

/catalog/cd/year = 1982

这个比较(称为一般的比较)运算符,如果左侧至少有一个项目“匹配”右侧的一个项目,就会返回 true。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接