cdm
cdm

Reputation: 799

How to write HTML tags in Perl using LibXML

I'm using LibXML to read/write an Android strings.xml file. Sometimes, I need to write html elements such as <b> or <i>. I've tried doing something like this (for example):

#!/usr/bin/env perl

#
# Create a simple XML document
#

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

my $doc = XML::LibXML::Document->new('1.0', 'utf-8');

my $root = $doc->createElement("resources");
my $tag = $doc->createElement("string");
$tag->setAttribute('name'=>'no_messages');
$tag->appendText("You have <b>no</b> messages");
$root->appendChild($tag);

$doc->setDocumentElement($root);
print $doc->toString();

But I end up with this:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="no_messages">You have &lt;b&gt;no&lt;/b&gt; messages</string>
</resources>

And what I'm looking for is this:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="no_messages">You have <b>no</b> messages</string>
</resources>

Upvotes: 1

Views: 406

Answers (2)

Borodin
Borodin

Reputation: 126762

XML::LibXML::Element objects have an appendWellBalancedChunk method that does exactly what you are asking for.

Here's a demonstration, based on your own sample code

use strict;
use warnings;

use XML::LibXML;

my $doc = XML::LibXML::Document->new(qw/ 1.0 utf-8 /);

my $root = $doc->createElement('resources');

my $tag = $doc->createElement('string');
$tag->setAttribute(name => 'no_messages');
$tag->appendWellBalancedChunk('You have <b>no</b> messages');

$root->appendChild($tag);

$doc->setDocumentElement($root);

print $doc->toString;

output

<?xml version="1.0" encoding="utf-8"?>
<resources><string name="no_messages">You have <b>no</b> messages</string></resources>

Upvotes: 0

mystery
mystery

Reputation: 19523

Since it doesn't support innerHTML, you have to manually add text and tags:

my $tag = $doc->createElement("string");
$tag->setAttribute('name'=>'no_messages');
$tag->appendText("You have ");
$b = $doc->createElement("b");
$b->appendText("no");
$tag->appendChild("b");
$tag->appendText(" messages");

That, or use the parser.

Upvotes: 1

Related Questions