Eric Evans
Eric Evans

Reputation: 670

How to delete xml element if it's empty simplexml

I have a xml with contents below.

<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>

All the module's in features element are empty.

I'm trying to not show these elements if they are empty, could some one point me in the right direction.

This is what I've tried.

$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();

But this doesn't work for and the elements are still shows. I'm new to simplexml, so any help is greatly appreciated.

Upvotes: 2

Views: 222

Answers (1)

splash58
splash58

Reputation: 26153

1st) close the tag because now your xml is not loaded by Dom parser

2nd) change this line node->$inst_child->module->removeChild($node); to

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

3rd) add echo to the last line to see the result

Here working code

Upvotes: 1

Related Questions