SimpleXML: Deleting an XPath Node
In this article, we'll explore how to effectively delete a parent node from an XML document using SimpleXML and XPath.
Understanding SimpleXML's Limitations
The provided code attempts to use SimpleXML to delete a parent node after finding it via XPath. However, SimpleXML's unset() function only removes the object reference stored in a variable, not the node itself.
DOMDocument to the Rescue
To overcome SimpleXML's limitations, consider using DOMDocument, which manipulates the structure of XML documents more directly.
Solution Using DOMDocument
Example Code and Output
$doc = new DOMDocument;
$doc->loadXML(...);
$item_id = 456;
$xpath = new DOMXpath($doc);
foreach($xpath->query('//items[info/item_id="' . $item_id . '"]') as $node) {
$node->parentNode->removeChild($node);
}
echo $doc->saveXML();
This code removes the
Conclusion
DOMDocument allows for more robust manipulation of XML documents, including direct removal of nodes. While SimpleXML can be convenient for basic XPath queries, DOMDocument is a more suitable choice for more complex XML manipulation tasks.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3