2010-03-18 81 views
0

我有一個元素的id屬性值。幫助使用XPath選擇

我只需要選擇其子女(不是所有的後代)。

我用

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

但會選擇所有後代並打印出來。我只想選擇1代的孩子。我怎麼能這樣做?

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

(導致層次是很長,所以fecthing所有後代將減緩過程下來,它不是智能抓取不必要的數據)。

+1

位在黑暗中刺,但是這可能我朝着正確的方向邁出的一步:'//實體[@ ID = 212323] /兒童:: * /文()'或'也許//實體[@ id = 212323]/child :: */child :: text()' – 2010-03-18 01:53:14

+0

不,它仍然提取id元素下的每個元素。 – 2010-03-18 01:55:47

+2

我想你是誤會。當你打印一個元素時,你打印它的所有子元素,對吧?即使您只選擇頂級兒童,如果您打印它們......您也可以打印所有內容。你需要重新考慮你的要求。 – Cheeso 2010-03-18 03:50:55

回答

4

您可以使用此:

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

只選擇那些沒有孩子的節點。如果這不夠好,你也期望像這樣的情況:

<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> 

你應該做更多的研究。在這個例子中text node 1text node 2被認爲是<this>元素的兒童。您需要找出(我不確定是否有可能)如何在xPath表達式中將這兩個節點與其他節點(如<notThis>asd</notThis>)區分開來。