[英]How to delete a node searched by attribute with its child nodes in xml by php
My XML file is given below I'm using the xml as external file: 下面是我的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>
From the above xml file I just want to delete the node where sclNo ="4" I mean the node bellow should not be in file after save. 从上面的xml文件中,我只想删除sclNo =“ 4”的节点,这意味着保存后不应在文件中添加以下节点。
<custscale sclNo="4" type="tbl1">
<scaleName>Custome Scale Table</scaleName>
<jsfunc>custTbl1</jsfunc>
</custscale>
It is requested to give the example using simpleXML. 请使用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();
?>
using simplexml
: 使用
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]);
}
It is requested to give the example using simpleXML
请使用simpleXML给出示例
This has been outlined in detail in Remove a child with a specific attribute, in SimpleXML for PHP . 在PHP的SimpleXML中,“删除具有特定属性的孩子”中对此进行了详细概述。
The key point is that you assign the element you want to unset to a variable - eg $element
- for example by querying the single or multiple nodes with an Xpath query ( standard example ) - and then unsetting it: 关键的一点是,你指定你想取消设置一个变量的元素-例如
$element
与XPath查询(查询单个或多个节点-例如标准的例子 ) -然后你重置它:
$element = $xml->xpath('/path/to/element/to[@delete = "true"]')[0];
unset($element[0]);
That is already it in simplexml. 在simplexml中已经足够了。 As you can see, this is really simple.
如您所见,这确实很简单。 A full example:
一个完整的例子:
$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');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.