Home  >  Article  >  Backend Development  >  How to Remove a Parent Node in SimpleXML Using XPath?

How to Remove a Parent Node in SimpleXML Using XPath?

Linda Hamilton
Linda HamiltonOriginal
2024-10-26 12:56:29155browse

How to Remove a Parent Node in SimpleXML Using XPath?

SimpleXML - Removing XPath Nodes

Question:

In SimpleXML, how can I delete a parent node associated with a specific element identified through XPath?

Problem Description:

Using the following code to find and remove an item with a specific item_id fails:

<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>

The unset($parent) statement does not eliminate the parent node.

Answer:

Directly calling unset() on an object variable ($parent in this case) only removes the object reference, not the node itself.

Solution Using DOMDocument:

<code class="php">$doc = new DOMDOcument;
$doc->loadxml(...XML string...);
$item_id = 456;

$xpath = new DOMXPath($doc);
foreach($xpath->query('//items[info/item_id="' . $item_id . '"]') as $node) {
  $node->parentNode->removeChild($node);
}</code>

This loop iterates through matching nodes, removes the parent node, and updates the $doc object.

Output:

<code class="xml"><?xml version="1.0"?>
<foo>
  <items>
    <info>
      <item_id>123</item_id>
    </info>
  </items>

  <items>
    <info>
      <item_id>789</item_id>
    </info>
  </items>
</foo></code>

The above is the detailed content of How to Remove a Parent Node in SimpleXML Using XPath?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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