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' 的前 2 个元素?

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

4

1 回答 1

4

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

(//post/misc[contains(tags,"animal")])[position() <= 2]
于 2012-11-19T10:10:25.647 回答