Comparing Mojo::DOM and HTML::Zoom
Introduction
Recently I have been using jQuery to select and manipulate HTML parts. I wanted to do something similar in Perl so I started playing with HTML::Zoom. In addition, I recently came across an article by tempire that introduced me to Mojo::DOM. This article provides a simple comparison of how the two tools do part of their job.
Initialize
Data
We need some data to work on. Let’s use this HTML fragment:
<div> <h1 id="hope">A new hope</h1> <p>A neat article about Selectors</p> </div>
Objects
Let’s get an object instance of both:
my $dom = Mojo::DOM->new; my $zoom = HTML::Zoom->new;
Parse
OK now let’s look are our first case of using these selectors by doing the first step of just parsing some HTML.
$dom ->parse($fragment) $zoom ->from_html($fragment)
Select
Let’s select the tag with the ‘hope’ id.
$dom
->parse($fragment)
->at('#hope')
$zoom
->from_html($fragment)
->select('#hope')
Replace
Let’s replace the text inside the ‘hope’ id’d node:
$dom
->parse($fragment)
->at('#hope')
->replace_inner($replacement)
$zoom
->from_html($fragment)
->select('#hope')
->replace_content($replacement)
Giving Back
Let’s parse, select, replace and then get the new HTML back (all of it).
$dom
->parse($fragment)
->at('#hope')
->replace_inner($replacement)
->root->to_xml
$zoom
->from_html($fragment)
->select('#hope')
->replace_content($replacement)
->to_html
Summary
| Method | Mojo::DOM | HTML::Zoom |
| Read HTML | parse | from_html |
| Select HTML | at | select |
| Replace Inner Text | replace_inner | replace_content |
| Emit HTML | to_xml | to_html |
Showing changes from previous revision. Removed | Added
