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

How to delete xml element if it's empty 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>

所有模块的 in features 元素都是空的。

如果这些元素为空,我尽量不显示这些元素,有人能给我指出正确的方向吗?

这是我试过的。

$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 的新手,所以非常感谢任何帮助。

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

加载

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

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

3rd) 最后一行加上echo 看结果

Here working code