Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does xpath query has Limit option like mysql

Tags:

limit

xpath

I want to limit number of result I receive from xpath query.

For example:-

$info = $xml->xpath("//*[firstname='Sheila'] **LIMIT 0,100**"); 

You see that LIMIT 0,100.

like image 780
Shiva Kumar R Avatar asked Feb 03 '23 06:02

Shiva Kumar R


1 Answers

You should be able to use "//*[firstname='Sheila' and position() <= 100]"

Edit:

Given the following XML:

<root> 
    <country.php desc="country.php" language="fr|pt|en|in" editable="Yes"> 
        <en/> 
        <in> 
            <cityList desc="cityList" language="in" editable="Yes" type="Array" index="No"> 
                <element0>Abu</element0>
                <element1>Agartala</element1>
                <element2>Agra</element2> 
                <element3>Ahmedabad</element3>
                <element4> Ahmednagar</element4> 
                <element5>Aizwal</element5>
                <element150>abcd</element150> 
            </cityList> 
        </in> 
    </country.php> 
</root>

You can use the following XPath to get the first three cities:

//cityList/*[position()<=3]

Results:

Node    element0    Abu
Node    element1    Agartala
Node    element2    Agra

If you want to limit this to nodes that start with element:

//cityList/*[substring(name(), 1, 7) = 'element' and position()<=3]

Note that this latter example works because you're selecting all the child nodes of cityList, so in this case Position() works to limit the results as expected. If there was a mix of other node names under the cityList node, you'd get undesirable results.
For example, changing the XML as follows:

<root> 
    <country.php desc="country.php" language="fr|pt|en|in" editable="Yes"> 
        <en/> 
        <in> 
            <cityList desc="cityList" language="in" editable="Yes" type="Array" index="No"> 
                <element0>Abu</element0>
                <dog>Agartala</dog>
                <cat>Agra</cat> 
                <element3>Ahmedabad</element3>
                <element4> Ahmednagar</element4> 
                <element5>Aizwal</element5>
                <element150>abcd</element150> 
            </cityList> 
        </in> 
    </country.php> 
</root>

and using the above XPath expression, we now get

Node    element0    Abu

Note that we're losing the second and third results, because the position() function is evaluating at a higher order of precedence - the same as requesting "give me the first three nodes, now out of those give me all the nodes that start with 'element'".

like image 129
Geoff Avatar answered Feb 15 '23 17:02

Geoff