tags:

views:

63

answers:

1

i've got an id attribute value for an element.

i want to select only its children (not all descendants).

i used

$childElements = $xml->xpath('//entity[@id=212323]');
print_r($childElements);

but that would select ALL descendants and print them out. i just want to select the 1 generation children. how could i do that?

<entity id=212323>
    <this>asd</this>
    <this>asd</this>
    <this>asd</this>
    <this>
        <notThis>asd</notThis>
        <notThis>asd</notThis>
        <notThis>asd</notThis>
    </this>
</entity>

(cause the hierarchy is very long, so fecthing all descendants would slow the process down, and its not smart to fetch unnecessary data).

+4  A: 

Hi there, you can use this:

//entity[@id=212323]/child::*[not(boolean(child::*))]

to select only the nodes which don't have children. If this is not good enough and you expect also cases like:

<entity id=212323>
    <this>asd</this>
    <this>asd</this>
    <this>asd</this>
    <this>
        text node 1
        <notThis>asd</notThis>
        <notThis>asd</notThis>
        <notThis>asd</notThis>
        text node 2
    </this>
</entity>

You should do some more research. In this example text node 1 and text node 2 are considered as children of <this> element. You need to find out (I am not sure if it is possible) how to differ this two nodes from the others(like <notThis>asd</notThis>) in your xPath expression.

Koynov