A followup: Why a regex *really* isn't good enough for HTML and XML, even for "simple" tasks

Your employer/interviewer/professor/teacher has given you a task with the following specification:

Given an XHTML file, find all the <div> tags with the class attribute "data"1 and extract their id attribute as well as their text content, or an empty string if they have no content. The text content is to be stripped of all non-word characters (\W) and tags, text from nested tags is to be included in the output. There may be other divs, other tags, and other attributes present anywhere, but divs with the class data are guaranteed to have an id attribute and not be nested inside each other. The output of your script is to be a single comma-separated list of the form id=text, id=text, .... You are to write your code first, and then you will be given a test file, guaranteed to be valid and standards-conforming, for which the expected output of your program is "Zero=, One=Monday, Two=Tuesday, Three=Wednesday, Four=Thursday, Five=Friday, Six=Saturday, Seven=Sunday"2.

Updates - Clarifications:
1 The class attribute should be exactly the string data (that is, ignoring the special treatment given to CSS classes). Examples below updated accordingly.
2 Your solution should be generic enough to support any arbitrary strings for the id and text content, and be easily modifiable to change the expected class attribute.

Ok, you think, I know Perl is a powerful text processing language and regexes are great! And you write your code and it works well for the test cases you came up with. ... But did you think of everything? Here's the test file you end up getting:

I encourage everyone to try and write a parser using your favorite module, be it:

Honorable mentions: Grimy for a regex solution and RonW for a regex-based parser :-)

I'll kick things off with Mojo::DOM (compacted somewhat, with potential for a lot more golfing or verboseness):

use warnings; use strict; use Mojo::DOM; my $dom = Mojo::DOM->new( do { open my $fh, '<', 'example.xhtml' or die $!; local $/; <$fh> } ); my $found = $dom->find('div[class="data"]')->map(sub { ( my $text = $_->all_text ) =~ s/\W//g; { id=>$_->attr('id'), text=>$text } })->to_array; my $out = join ', ', map { $_->{id}.'='.$_->{text} } @$found; print $out,"\n"; $out eq "Zero=, One=Monday, Two=Tuesday, Three=Wednesday, " ."Four=Thursday, Five=Friday, Six=Saturday, Seven=Sunday" ? print "Good!\n" : die "BAD!\n";

Updates after posting: Minor updates to wording for clarification. Added test more cases to example file. 2017-10-17: Replaced &nbsp; as discussed in the replies. Switched from XHTML 1.0 Transitional to XHTML 1.0 Strict. Added Schema declaration. Added output check to Mojo::DOM example. 2017-10-20: A few minor updates to text.

Update 2017-10-18: Thank you very much to everyone who has replied and posted their solutions so far, keep em coming! :-)


In reply to Parsing HTML/XML with Regular Expressions by haukex

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.