简体   繁体   中英

PHP domDocument remove element by attribute value

I want to remove the element for an attribute value which is declared by some variable. I have a xml like this:

<configuration name="acl.conf" description="Network Lists">
  <network-lists><!-- IMS ALLOW ONLY -->
    <list name="test" default="deny">
      <node type="allow" cidr="11.11.11.101/32"/>
   </list>
   <list name="customer" default="deny" type="allow">
      <node type="allow" cidr="10.13.13.193/32"/>
      <node type="allow" cidr="10.13.13.194/32"/>
      <node type="allow" cidr="10.13.13.3/32"/>
      <node type="allow" cidr="10.13.13.2/32"/>
   </list>
  </network-lists>
</configuration>

Can anyone help me with the php code? I tried something like this but it doesn't work.

    <?php
$doc = new DOMDocument; 
$id = $_GET['id'];
$doc->load('acl.conf.xml');

$searchNode = $doc->getElementsByTagName( "node" );

foreach( $searchNode as $searchNode )
{
    $valueID = $searchNode->getAttribute('cidr');

    } 
?>

Assuming $_GET['id'] is the cidr value you want to remove, I'd use XPath

$xpath = new DOMXPath($doc);
$nodes = $xpath->query('//node[@cidr="' . $id . '"]')
foreach ($nodes as $node) {
    $node->parentNode->removeChild($node);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM