如果它是空的simplexml,如何删除xml元素

时间:2015-07-14 18:06:26

标签: php xml simplexml

我有一个内容如下的xml。

<build id="1.2.3" name="Build 1.2.3" master="Ghost">
    <features>
        <module id="glob" name="Global Module"></module>
        <module id="sis" name="Instrumented System Module"></module> <!-- placed here for ordering with instance-specific tasks -->
        <module id="tracker" name="Action Item Tracker Module"></module> <!-- placed here for ordering with instance-specific tasks -->
    <!-- placed here for ordering with instance-specific tasks -->
    </features>
    <fixes>
        <module id="sis" name="Instrumented System Module"></module> <!-- placed here for ordering with instance-specific tasks -->
        <module id="omi" name="Operate/Maintain Module">
            <description id="879">Eric is testing this thing to make sure it works</description>
        </module>
        <module id="fsa" name="Functional Safety Assessments Module"></module> <!-- placed here for ordering with instance-specific tasks -->
        <module id="personnel" name="Personnel Module"></module> <!-- placed here for ordering with instance-specific tasks -->
        <module id="general" name="General">
            <description id="879">Bug Fixed Delete and Cascade</description>
        </module>
    </fixes>
</build>

feature元素中的所有模块都是空的。

我试图不显示这些元素,如果它们是空的,可能有人指出我正确的方向。

这就是我尝试过的。

$doc = new DOMDocument;
$doc->preserveWhiteSpace = false;
$doc->loadXML($master_build_info_sorted_old);

$xpath = new DOMXPath($doc);

foreach ($xpath->query('//*[not(node())]') as $node) {
        $node->$inst_child->module->removeChild($node);
}
$doc->formatOutput = true;
$doc->saveXML();

但这不起作用,元素仍然显示。我是simplexml的新手,所以非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

1st)关闭标签,因为现在你的xml没有被Dom解析器加载

2)将此行node->$inst_child->module->removeChild($node);更改为

   $node->parentNode->removeChild($node);

3rd)将echo添加到最后一行以查看结果

Here working code