在PHP中从XML中删除父节点

时间:2014-10-29 15:33:04

标签: php xml dom xpath simplexml

我有一些像这样的XML:

<tree path="Masters">
    <item  id="Masters\2014"  name="2014"  isFolder="true"  path="Masters\2014" >
        <item  id="Masters\2014\Brochures"  name="Brochures"  isFolder="true"  path="Masters\2014\Brochures" >
            <item  id="Masters\2014\Brochures\PLEASE DO NOT COPY"  name="PLEASE DO NOT COPY"  isFolder="true"  path="Masters\2014\Brochures\PLEASE DO NOT COPY" >
                <item  id="a4e6f520-9b26-42c0-af92-bbd17ab6e8b6"  name="00001"  isFolder="false"  path="Masters\2014\Brochures\PLEASE DO NOT COPY\00001.xml" >
                    <fileInfo fileSize="141.23 Kb"></fileInfo>
                </item>
                <item  id="6b8cbff5-cf03-4d2c-9931-bb58d7f3ff8a"  name="00002"  isFolder="false"  path="Masters\2014\Brochures\PLEASE DO NOT COPY\00002.xml" >
                    <fileInfo fileSize="192.19 Kb"></fileInfo>
                </item>
            </item>
            <item  id="65773008-4e64-4316-92dd-6a535616ccf6"  name="Sales Brochure A4"  isFolder="false"  path="Masters\2014\Brochures\Sales Brochure A4.xml" >
                <fileInfo fileSize="34.38 Kb"></fileInfo>
            </item>
        </item>
    </item>
</tree>

我需要删除属性name与正则表达式/^[0-9]{5,6}$/匹配的所有节点(包括其子节点)(长度为5或6位数字)并删除其父< / em>的

除此之外,我还需要删除属性isFolder设置为false的所有元素。

我到目前为止的代码是:

<?php

$simple_xml = simplexml_load_string($xml);

//Foreach item tag
foreach($simple_xml->xpath('//item') as $item) {

    //This correctly identifies the nodes
    if(preg_match('/^[0-9]{5,6}$/', $item->attributes()->name)) {

        //This doesn't work. I'm guessing chaining isn't possible?
        $dom = dom_import_simplexml($item);
        $dom->parentNode->parentNode->removeChild($dom);


    } else {

        //This correctly identifies the nodes
        if($item->attributes()->isFolder == 'false') {

            //This part works correctly and removes the nodes as required
            $dom = dom_import_simplexml($item);
            $dom->parentNode->removeChild($dom);

        }

    }

}

//At this point $simple_xml should contain the rebuilt xml tree in simplexml style

?>

从评论中可以看出,我有isFolder部分正常工作,但是当项目节点的属性{{1}时我似乎无法移除父节点具有5或6位长名称的值。

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

主要问题是您试图从其祖父母中移除<item>节点。下面的代码已经过重新计算,因此父级将从祖父母中移除。

$simple_xml = simplexml_load_string($xml);
foreach ($simple_xml->xpath('//item') as $item) {
  if (preg_match('/^[0-9]{5,6}$/', $item['name'])) {
    $dom = dom_import_simplexml($item);
    $parent = $dom->parentNode;
    if ($parent && $parent->parentNode) {
      $parent->parentNode->removeChild($parent);
    }
  } else if ($item['isFolder'] == 'false') {
    $dom = dom_import_simplexml($item);
    $dom->parentNode->removeChild($dom);
  }
}