Home > Backend Development > PHP Tutorial > How Can I Delete an XPath Node Using SimpleXML and DOMDocument?

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

Patricia Arquette
Release: 2024-10-26 21:25:29
Original
480 people have browsed it

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

<code class="php">$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();</code>
Copy after login

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.

The above is the detailed content of How Can I Delete an XPath Node Using SimpleXML and DOMDocument?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template