我有一個具有以下結(jié)構(gòu)的 XML 文件:<r> <a> <i> <k>1</k> <d>d1</d> </i> <i> <k>3</k> <d>d3</d> </i> </a> <b> <i> <k>1</k> <d>rd1</d> </i> <i> <k>2</k> <d>id2</d> </i> <i> <k>3</k> <d>rd3</d> </i> </b></r>我選擇i下面的節(jié)點/r/a并迭代它們以查找下面的關(guān)聯(lián)節(jié)點/r/b并檢索其節(jié)點的值,d如下所示:$data = [];$nodes = $domXPath->evaluate('/r/a/i');foreach($nodes as $node) { $key = $domXPath->evaluate('string(k)', $node); $data[] = $domXpath->evaluate("string(/r/b/i[k=$key]/d)", $node);}這會產(chǎn)生正確的結(jié)果$data:[ "rd1", "rd3",]我的問題是是否可以在不將密鑰拔出 PHP 的情況下執(zhí)行此操作,例如:$data = [];$nodes = $domXPath->evaluate('/r/a/i');foreach($nodes as $node) { $data[] = $domXpath->evaluate("string(/r/b/i[k=initial-context()/k]/d)", $node);}
1 回答

鳳凰求蠱
TA貢獻(xiàn)1825條經(jīng)驗 獲得超4個贊
您可以使用單個 XPath 來完成此操作:
$nodes = $domXPath->evaluate('/r/b/i[k = /r/a/i/k]/d'); foreach($nodes as $node) $data[] = $node->textContent;
該表達(dá)式表示,對于每個/r/b/i
節(jié)點,僅當(dāng)其節(jié)點與 下的k
相應(yīng)節(jié)點匹配時才允許。k
/r/a/i
- 1 回答
- 0 關(guān)注
- 157 瀏覽
添加回答
舉報
0/150
提交
取消