1

i removed some elements from a xml file with simpledom.

the code:

$this->xmlDocument->removeNodes("//entity[name='mac']");

here is the initial file:

<entity id="1000070">
    <name>apple</name>
    <type>category</type>
    <entities>
        <entity id="7002870">
            <name>mac</name>
            <type>category</type>
        </entity>
        <entity id="7024080">
            <name>iphone</name>
            <type>category</type>
        </entity>
        <entity id="7024080">
            <name>ipad</name>
            <type>category</type>
        </entity>
    </entities>
</entity>

the file afterwards:

<entity id="1000070">
    <name>apple</name>
    <type>category</type>
    <entities>




        <entity id="7024080">
            <name>iphone</name>
            <type>category</type>
        </entity>
        <entity id="7024080">
            <name>ipad</name>
            <type>category</type>
        </entity>
    </entities>
</entity>

i wonder how i could also remove the blank lines that are left after i ran the removal code?

thanks!

never_had_a_name
  • 90,630
  • 105
  • 267
  • 383
  • You can remove the blanks , but you will probably not end up with nicely indented (prettified) XML. You will probably end up with `` on the same line. – nl-x Jun 17 '13 at 08:45

2 Answers2

0

Just in case you'd like to remove ALL these blank spaces for your output, there's a simple way below:

$this->xmlDocument->removeNodes(
    "//entity[name='mac'] | //text()[normalize-space(.) = '']"
);
0

You can target the whitespace text nodes with XPath.

If the nodes you want to remove are //entity[name='mac'] then the whitespace text node before it would be

//text()[normalize-space(.) = ''][following-sibling::entity[position()=1][name='mac']]

And then, you can remove both nodesets by using the | operator and your command becomes:

$this->xmlDocument->removeNodes(
    "//entity[name='mac'] | //text()[normalize-space(.) = ''][following-sibling::entity[position()=1][name='mac']]"
);
Josh Davis
  • 28,400
  • 5
  • 52
  • 67