Are you sure you are selecting the right nodes?
'/html/body//div/ul/li' will select list items, not the list itself.

Given this HTML:

<div> <ul> <li>one</li> <li>two</li> <li>three</li> </ul> <!-- List with 2 empty List Items --> <ul> <li></li> <li>two</li> <li></li> </ul> <!-- Empty List --> <ul> </ul> </div
Run on list items, it does delete empty items:
sub delete_empty_list_item { my $xhtml = HTML::TreeBuilder->new; $xhtml->implicit_tags(1); $xhtml->parse_file($file); for my $list_item ($xhtml->findnodes('/html/body//div/ul/li')) { if ($list_item->is_empty) { print qq(DELETE\n); $list_item->delete(); } } print $xhtml->as_XML_indented; $xhtml->eof; } OUTPUT: <div> <ul> <li>one</li> <li>two</li> <li>three</li> </ul> <ul> <li>two</li> </ul> <ul> </ul> </div>
Run on list elements, it deletes the list itself:
sub delete_empty_list { my $xhtml = HTML::TreeBuilder->new; $xhtml->implicit_tags(1); $xhtml->parse_file($file); for my $list ($xhtml->findnodes('/html/body//div/ul')) { if ($list->is_empty) { print qq(DELETE\n); $list->delete(); } } print $xhtml->as_XML_indented; $xhtml->eof; } OUTPUT: <div> <ul> <li>one</li> <li>two</li> <li>three</li> </ul> <ul> <li></li> <li>two</li> <li></li> </ul> </div>
You could combine the two if you need to delete both empty items and empty lists.

 


In reply to Re: Deleting nodes with HTML::TreeBuilder::XPath by tangent
in thread Deleting nodes with HTML::TreeBuilder::XPath by mldvx4

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.