the node is replaced by a blank line.
The node wasn't replaced with anything. You started with
< i t e m 1 / > LF < i t e m 2 / > LF < i t e m 3 / > LF
If you delete the second element, you get
< i t e m 1 / > LF LF < i t e m 3 / > LF
Nothing is added in its place.
You want to delete the leading newline of node that follows if it's a text node.
use strict; use warnings; use open ':std', ':locale'; use XML::LibXML qw( XML_TEXT_NODE ); sub remove_newline_that_follows { my ($node) = @_; my $next_node = $node->nextSibling() or return; $next_node->nodeType() == XML_TEXT_NODE or return; my $text = $next_node->data(); $text eq "" and return remove_newline_that_follows($next_node); $text =~ s/^\n// and $next_node->setData($text); } sub remove_node { my ($node) = @_; $node->parentNode()->removeChild($node); } my $doc = XML::LibXML->load_xml( string => <<'__EOI__' ); <root> <item1/> <item2/> <item3/> </root> __EOI__ my $root = $doc->documentElement(); my ($node) = $root->findnodes('//item2') or die; remove_newline_that_follows($node); remove_node($node); print $root->toString();
Update: Tested and fixed the broken XPath (by replacing it). I was using the following (marked as untested):
my ($next_node) = $node->findnodes( 'following-sibling::*[ position()=1 and text() ]') or return;
The correct XPath is
my ($next_node) = $node->findnodes( 'following-sibling::node()[ position()=1 and self::text() ]') or return;
Of course, what I used instead is much clearer (and surely faster).
my $next_node = $node->nextSibling() or return; $next_node->nodeType() == XML_TEXT_NODE or return;
In reply to Re: Removing whitespace from deleted items in XML::LibXML
by ikegami
in thread Removing whitespace from deleted items in XML::LibXML
by alan_olsen
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |