【问题标题】:How to delete xml element if it's empty simplexml如果它是空的simplexml,如何删除xml元素
【发布时间】:2015-07-14 18:06:26
【问题描述】:

我有一个包含以下内容的 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 的新手,非常感谢任何帮助。

【问题讨论】:

  • 这不是 simplexml,就像在你的标题和标签中一样

标签: php xml simplexml


【解决方案1】:

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

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

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

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

Here working code

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-25
    • 1970-01-01
    • 1970-01-01
    • 2018-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-26
    相关资源
    最近更新 更多