PHP SimpleXML xpath: 包含和位置

5
以下是我的PHP代码:
$xml = new SimpleXMLElement('data.xml', null, true);
$q = $xml->xpath('post/misc[contains(tags,"animal")][position() <= 2]');

以下是XML文件:

<?xml version="1.0" encoding="UTF-8" ?>
<posts>
    <post>
        <id>1</id>
        <misc>
            <tags>animal,tiger</tags>
            <prio>0.5</prio>
        </misc>
    </post>
    <post>
        <id>2</id>
        <misc>
            <tags>plant,coconut</tags>
            <prio>0.5</prio>
        </misc>
    </post>
    <post>
        <id>3</id>
        <misc>
            <tags>animal,lion</tags>
            <prio>0.5</prio>
        </misc>
    </post>
    <post>
        <id>4</id>
        <misc>
            <tags>animal,monkey</tags>
            <prio>0.5</prio>
        </misc>
    </post>
</posts>

如何获取标签包含“animal”的前两个元素?

XPath结果应为post:id=1post:id=3,但它似乎返回了所有包含animal的元素。

1个回答

4
将主要XPath部分放在()括号中,例如:
(//post/misc[contains(tags,"animal")])[position() <= 2]

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