【发布时间】:2014-10-29 15:33:03
【问题描述】:
我有一些这样的 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
?>
从 cmets 可以看出,isFolder 部分可以根据需要工作,但是当项目节点的属性 name 的值为 5 或 6 时,我似乎无法删除父节点数字长名称。
提前感谢您的帮助。
【问题讨论】:
标签: php xml dom xpath simplexml