http://qs1969.pair.com?node_id=1201438

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! :-)