"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Delete an XPath Node Using SimpleXML and DOMDocument?

How Can I Delete an XPath Node Using SimpleXML and DOMDocument?

Published on 2024-11-08
Browse:763

How Can I Delete an XPath Node Using SimpleXML and DOMDocument?

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

  1. Create a DOMDocument object and load the XML file into it.
  2. Use XPath to query and select the target node.
  3. Remove the parent node using $node->parentNode->removeChild($node).

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 node for the product with item_id 456, resulting in a modified XML document without that node.

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.

Latest tutorial More>

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