我正在使用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 <b>no</b> messages</string>
</resources>
我正在寻找的是:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="no_messages">You have <b>no</b> messages</string>
</resources>
答案 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>