i have xml:
<root> <level name="main"> <level name="sub_1"> <content id="abc123" /> </level> </level> </root> i search node id abc123 , delete <content> , parent <level>
so end result be:
<root> <level name="main"> </level> </root> i have tried in php without result, doing wrong?
$doc = new domdocument; $doc->loadxml($xml_from_file); $xpath = new domxpath($doc); $node_list = $xpath->query("content[@id='abc123']/parent::*"); $node = $node_list->item(0); $doc->removechild($node);
here 2 issues source.
the expression match child nodes. need start // match node: //content[@id='abc123']/parent::*.
the found node not child of document so, need remove own parent: $node->parentnode->removechild($node);.
i suggest using foreach avoid problems if node doesn't exists.
$document = new domdocument; $document->loadxml($xmlstring); $xpath = new domxpath($document); foreach ($xpath->evaluate("//content[@id='abc123']/parent::*") $node) { $node->parentnode->removechild($node); } echo $document->savexml();
Comments
Post a Comment