PHP SimpleXML xpath:包含和位置

时间:2012-11-19 08:50:33

标签: xml xpath position contains

这是我的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'的2个第一个元素?

xpath结果应为post:id=1post:id=3,但可以看到它返回包含animal的所有元素。

1 个答案:

答案 0 :(得分:4)

将主XPath部分放在()括号中,即:

(//post/misc[contains(tags,"animal")])[position() <= 2]