0

How does one with perl change an html element's value using the html element's ID. How do you do this in the code.

For example:

        <div id="container">
            <form id="form" action="../code.cgi" method="post">
                <label id="lblMessage" class="text">Message</label>
            </form>
        </div>

How would I change the label's text in my perl script?

John
  • 21
  • possible duplicate of https://stackoverflow.com/questions/8411684/xmllibxml-replace-element-value – Robert Feb 02 '16 at 00:24
  • @Robert, That question is actually a more specific case of this one (being limited to XML::LibXML). Furthermore, this question is well phrased and well answered for future reference. If one of two should be closed, I would prefer for it to be the other one (even though the leading answer with >10 votes is mine). – ikegami Feb 02 '16 at 01:09

2 Answers2

2

Get an HTML or XML parser find the element (e.g., by XPath expression), and remove all its child text nodes, and add a new text node with the text you want.

use strict;
use warnings;
use XML::LibXML;

my $dom = XML::LibXML->load_html(location => 'myfile.html');
my $xpath = XML::LibXML::XPathContext->new($dom);
foreach my $label ($xpath->findnodes('//label[@id="lblMessage"]')) {
    $label->removeChildNodes();
    $label->addChild($dom->createTextNode("new text"));
}

Caveat: if there are other nodes (elements, like <b> or <span>) in your label, these get removed as well.

You probably need to add some code to write the modified html back to a file.

Robert
  • 7,394
  • 40
  • 45
  • 64
2

I, personally like HTML::TreeBuilder for this sort of task.

use HTML::TreeBuilder;

my $html = <<END;
    <div id="container">
        <form id="form" action="../code.cgi" method="post">
            <label id="lblMessage" class="text">Message</label>
        </form>
    </div>
END

my $root = HTML::TreeBuilder->new_from_content( $html );
$root->elementify();  # Become a tree of HTML::Element objects.

my $message = $root->find_by_attribute( 'id', 'lblMessage' )
    or die "No such element";

$message->delete_content();
$message->push_content('I am new stuff');

print $root->as_HTML();
daotoad
  • 26,689
  • 7
  • 59
  • 100