【问题标题】:How to delete a node searched by attribute with its child nodes in xml by php如何通过php删除按属性搜索的节点及其在xml中的子节点
【发布时间】:2013-04-29 22:32:45
【问题描述】:

下面给出了我的 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举例。

【问题讨论】:

  • @Rolando-Isidoro 你能回答我的问题吗?
  • 您正在解决哪个具体问题?您遇到错误的代码在哪里?什么具体不起作用?你在哪里撞到石头?任何错误信息?本网站上现有的哪些解决方案不适合您?而且写“提前致谢”经常被其他用户认为是粗鲁的,最好不要那样做。
  • -1,因为没有提供自己的代码和粗鲁的反馈给那些花时间和精力回答的人。

标签: php xml simplexml


【解决方案1】:
<?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

【讨论】:

  • 我发布的确切代码可能不适用于您的程序。但相信我,这就是删除特定节点的方式; )。查看提供的链接。
【解决方案2】:

请用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');

See it in action.

【讨论】:

  • 不错,从来不知道如何通过路径 +1 做到这一点
【解决方案3】:

使用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]);
}

【讨论】:

  • @Sonnet:当然可以。你在某处有错误。在原始问题中发布您的代码,这比发布“不工作”要容易得多。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-22
  • 1970-01-01
  • 2016-11-13
  • 1970-01-01
  • 1970-01-01
  • 2014-08-01
相关资源
最近更新 更多