我的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提供示例。
答案 0 :(得分:2)
<?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();
?>
取自here
答案 1 :(得分:0)
使用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]);
}
答案 2 :(得分:0)
要求使用simpleXML
给出示例
Remove a child with a specific attribute, in SimpleXML for PHP已详细介绍了这一点。
关键是您要将要取消设置的元素分配给变量 - 例如$element
- 例如,通过使用Xpath查询(standard example)查询单个或多个节点 - 然后unsetting:
$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');