SimpleXML-删除xpath节点 [英] SimpleXML - Remove xpath node

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

问题描述

对于如何删除可以通过xpath搜索找到的某些对象的父节点,我有些困惑:

I'm a little confused as to how I can delete a parent node of something which I can find via an xpath search:

$xml = simplexml_load_file($filename);
$data = $xml->xpath('//items/info[item_id="' . $item_id . '"]');
$parent = $data[0]->xpath("parent::*");
unset($parent);

因此,它找到了项目ID,在那里没有问题-但是未设置未摆脱此<items>节点.我要做的就是删除此产品的<items>...</items>.显然,xml文件中有许多<items>节点,因此它不能执行unset($xml->data->items),因为这会删除所有内容.

So, it finds the item id, no problems there - but the unset isn't getting rid of this <items> node. All I want to do is remove the <items>...</items> for this product. Obviously, there are loads of <items> nodes in the xml file so it can't do unset($xml->data->items) as that would delete everything.

任何赞赏的想法:-)

推荐答案

<?php
$xml = new SimpleXMLElement('<a><b/></a>');
unset($xml->b);
echo $xml->asxml();

这可以按预期工作(从文档中删除< b/>元素),因为 __ unset()方法(或模块代码中的等效方法)被调用.
但是,当您调用unset($parent);时,它只会删除$ parent中存储的对象引用,但不会影响对象本身或$ xml中存储的文档. 为此,我将恢复为 DOMDocument .

this works as intended (removing the <b/> element fromt he document) because the __unset() method (or the equivalent in the modules code) is called.
But when you call unset($parent); it only removes the object reference stored in $parent, but it doesn't affect the object itself or the document stored in $xml. I'd revert to DOMDocument for this.

<?php
$doc = new DOMDOcument;
$doc->loadxml('<foo>
  <items>
    <info>
      <item_id>123</item_id>
    </info>
  </items>
  <items>
    <info>
      <item_id>456</item_id>
    </info>
  </items>
  <items>
    <info>
      <item_id>789</item_id>
    </info>
  </items>
</foo>');
$item_id = 456;

$xpath = new DOMXpath($doc);
foreach($xpath->query('//items[info/item_id="' . $item_id . '"]') as $node) {
  $node->parentNode->removeChild($node);
}
echo $doc->savexml();

打印

<?xml version="1.0"?>
<foo>
  <items>
    <info>
      <item_id>123</item_id>
    </info>
  </items>

  <items>
    <info>
      <item_id>789</item_id>
    </info>
  </items>
</foo>

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

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