简体   繁体   English

xml删除php中的子节点

[英]xml remove child node in php

I'm trying to remove the "druzenje" element by the 'id' attribute. 我正在尝试通过'id'属性删除“ druzenje”元素。 I know that for that to happen, i have to remove all the child nodes from that element. 我知道要做到这一点,我必须从该元素中删除所有子节点。

<?xml version="1.0" encoding="utf-8"?>
<druzenja>
    <druzenje id="1">
        <podaci attribute="some-data"/>
    </druzenje>
    <druzenje id="3">
        <podaci attribute="some-data"/>
    </druzenje>
</druzenja>

The code to remove is this... 要删除的代码是这样的...

    $druzenja = $this->dom->getElementsByTagName('druzenje');

    foreach($druzenja as $node) {
        if($node->getAttribute('id') == $id) {
            $podaciNodeList = $node->getElementsByTagName('podaci');
            foreach($podaciNodeList AS $podaciNode) {
                $node->removeChild($podaciNode);
            }

            $this->dom->documentElement->removeChild($node);
            return true;
        }
    }

I presume that removing a node by an 'id' attribute could be bad design but I based a lot of code on that and so far, there hasn't been any problems. 我认为通过'id'属性删除节点可能是不好的设计,但是我基于此编写了大量代码,到目前为止,还没有任何问题。 I also have a code that removes the "podaci" element that works in a similar way and it does that with no problems, but here it fails. 我也有一个代码,删除了以类似方式工作的“ podaci”元素,并且这样做没有问题,但是在这里失败了。 The code won't remove the "podaci" and "druzenje" element even though removeChild() returns the DomElement object which means its successful but it's not. 该代码不会删除“ podaci”和“ druzenje”元素,即使removeChild()返回DomElement对象也意味着它成功了,但是没有成功。

Any ideas? 有任何想法吗?

$element = $this->dom->getElementById($id);
$element->parentNode->removeChild($element);

Someone kill me. 有人杀了我 I haven't been saving. 我没有存钱。 I apologize for wasting someone's precious time. 对于浪费某人的宝贵时间,我深表歉意。

getElementsByTagName() returns "live" result that you remove the elements from the DOM. getElementsByTagName()返回“实时”结果,即您从DOM中删除了元素。 Copy it to an array to get a fixed list. 将其复制到数组以获取固定列表。

$druzenja = iterator_to_array(
  $this->dom->getElementsByTagName('druzenje')
);

foreach ($druzenja as $node) {
  if ($node->getAttribute('id') == $id) {
    $node->parentNode->removeChild($node);
  }
}

Xpath would allow you to use more complex conditions. Xpath将允许您使用更复杂的条件。 The result is not live. 结果不是实时的。

$xpath = new DOMXpath($this->dom);
foreach ($xpath->evaluate('//druzenje[@id="'.$id.'"]') as $node) {
  $node->parentNode->removeChild($node);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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