如何使用LibXML在Perl中编写HTML标记

时间:2015-02-03 01:34:30

标签: html perl libxml2

我正在使用LibXML来读/写Android strings.xml文件。有时,我需要编写html元素,例如<b><i>。我尝试过做这样的事情(例如):

#!/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();

但我最终得到了这个:

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

我正在寻找的是:

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

2 个答案:

答案 0 :(得分:1)

由于它不支持innerHTML,您必须手动添加文字和标签:

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");

那,或使用parser

答案 1 :(得分:0)

XML::LibXML::Element个对象的appendWellBalancedChunk方法完全符合您的要求。

以下是基于您自己的示例代码

的演示
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;

<强>输出

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