如何删除一个节点的属性搜索与它的子节点在xml由php


How to delete a node searched by attribute with its child nodes in xml by php

我的XML文件如下,我使用XML作为外部文件:

<?xml version="1.0"?>
<custscales>
    <custscale sclNo="1" type="lin">
        <scaleName>Custom Scale Lin</scaleName>
        <jsfunc>custLin</jsfunc>
    </custscale>
    <custscale sclNo="2" type="map">
        <scaleName>Custome Scale Map</scaleName>
        <jsfunc>custMap</jsfunc>
    </custscale>
    <custscale sclNo="3" type="pol">
        <scaleName>Custome Scale Pol</scaleName>
        <jsfunc>custPol</jsfunc>
    </custscale>
    <custscale sclNo="4" type="tbl1">
        <scaleName>Custome Scale Table</scaleName>
        <jsfunc>custTbl1</jsfunc>
    </custscale>
</custscales>

从上面的xml文件中,我只想删除节点,其中sclNo ="4",我的意思是下面的节点在保存后不应该在文件中。

    <custscale sclNo="4" type="tbl1">
        <scaleName>Custome Scale Table</scaleName>
        <jsfunc>custTbl1</jsfunc>
    </custscale>

要求使用simpleXML给出示例

<?php
$doc = new DOMDocument; 
$doc->load('theFile.xml');
$thedocument = $doc->documentElement;
$list = $thedocument->getElementsByTagName('custscale ');

$nodeToRemove = null;
foreach ($list as $domElement){
  $attrValue = $domElement->getAttribute('sclNo');
  if ($attrValue == '4') {
    $nodeToRemove = $domElement; //will only remember last one- but this is just an example :)
  }
}
if ($nodeToRemove != null)
$thedocument->removeChild($nodeToRemove);
echo $doc->saveXML(); 
?>

从这里取

要求使用simpleXML

给出示例

这在中有详细的概述,在SimpleXML for PHP中删除具有特定属性的子元素。

关键是您将想要取消设置的元素分配给一个变量—例如$element—例如通过使用Xpath查询单个或多个节点(标准示例)—然后取消设置:

$element = $xml->xpath('/path/to/element/to[@delete = "true"]')[0];
unset($element[0]);

在simplexml中已经是这样了。如你所见,这真的很简单。完整示例:

$xml = simplexml_load_string(<<<BUFFER
<path>
 <to>
   <element>
     <to delete="true" />
   </element>
 </to>
</path>
BUFFER;
);
$element = $xml->xpath('/path/to/element/to[@delete = "true"]')[0];
unset($element[0]);
$xml->asXML('php://output');

using simplexml:

$xml = simplexml_load_string($x); // assume XML in $x
$i = count($xml); 
for ($i; $i > 0; $i--) {   
    $cs = $xml->custscale[$i];
    if ($cs['sclNo'] == "4") unset($xml->custscale[$i]);
}