What is the to_string method in Mojo::DOM?
Overview
The to_string method renders the given node and its contents to an HTML/XML string. This method is provided by the Mojo::DOM module, which is an HTML/XML
Syntax
my $str = $dom->to_string;
Return value
This method returns a string of HTML/XML for the given node and its contents.
Let’s take a look at an example.
Example
In the following example, we will try to render the given node and its contents to an HTML/XML string.
Code
use 5.010;use Mojo::DOM;# Parse the htmlmy $dom = Mojo::DOM->new('<div>Inside div <p id="a">Inside paragraph </p>After paragraph<h1>Inside h1</h1>After h1<h2>Inside h2</h2></div>');# get rendered stringmy $str = $dom->at('p')->to_string;say $str
Explanation
- Line 2: We import the
Mojo::DOMmodule. - Line 5: We construct a
Mojo::DOMobject with thenewkeyword and parse the HTML. We then store it in the$dom .scalar A scalar is a variable that stores a single unit of data. - Line 10: We get the first descending element,
p, using theat()method. We render thepnode and its contents to the HTML/XML string using theto_stringmethod. - Line 12: We print the
strstring returned in line 10.