我有一些类似的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位长的名称)匹配的所有节点(包括它的子节点),还需要删除它的父节点。
除此之外,我还需要删除属性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
部分可以根据需要工作,但当项节点的属性name
的值为5或6位长名称时,我似乎无法删除父节点。
提前感谢您的帮助。
主要问题是您试图从<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);
}
}