xml删除php中的子节点 [英] xml remove child node in php

查看:25
本文介绍了xml删除php中的子节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过 'id' 属性删除druzenje"元素.我知道要做到这一点,我必须从该元素中删除所有子节点.

I'm trying to remove the "druzenje" element by the 'id' attribute. 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;
        }
    }

我认为通过 'id' 属性删除节点可能是糟糕的设计,但我基于此编写了大量代码,到目前为止,还没有出现任何问题.我还有一个代码,它删除了以类似方式工作的podaci"元素,它没有问题,但在这里它失败了.代码不会删除podaci"和druzenje"元素,即使 removeChild() 返回 DomElement 对象,这意味着它成功但它不是.

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. 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. 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.

有什么想法吗?

推荐答案

getElementsByTagName() 返回从 DOM 中删除元素的实时"结果.将其复制到数组中以获得固定列表.

getElementsByTagName() returns "live" result that you remove the elements from the 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 将允许您使用更复杂的条件.结果不直播.

Xpath would allow you to use more complex conditions. The result is not live.

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

这篇关于xml删除php中的子节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆