How to Remove an XPath Node in SimpleXML Without Losing the Entire Structure?

Susan Sarandon
Release: 2024-10-26 00:21:02
Original
509 people have browsed it

How to Remove an XPath Node in SimpleXML Without Losing the Entire Structure?

How to Remove an XPath Node with SimpleXML

Finding and removing an XML node using XPath queries can be a challenge in SimpleXML. This article addresses the issue of deleting a parent node identified through an XPath search.

Consider the following example:

<code class="php">$xml = simplexml_load_file($filename);
$data = $xml->xpath('//items/info[item_id="' . $item_id . '"]');
$parent = $data[0]->xpath("parent::*");
unset($parent);</code>
Copy after login

In this code, the goal is to delete the parent node for a specific product identified by its . However, using unset($parent) does not remove the node because it only eliminates the reference to the object stored in $parent.

A solution is to revert to using DOMDocument for this task:

<code class="php">$doc = new DOMDocument;
$doc->loadxml('<foo>
  <items>
    <info>
      <item_id>123</item_id>
    </info>
  </items>
  <items>
    <info>
      <item_id>456</item_id>
    </info>
  </items>
  <items>
    <info>
      <item_id>789</item_id>
    </info>
  </items>
</foo>');
$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 will remove the node containing the specified from the XML document. It uses the removeChild() method to delete the node from its parent.

The above is the detailed content of How to Remove an XPath Node in SimpleXML Without Losing the Entire Structure?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!