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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.