我如何使用Perl模块XML :: LibXML创建xml内容/文档

时间:2019-03-21 12:08:18

标签: perl xml-parsing

如何使用XML :: LibXML在perl中生成以下xml内容

<?xml version="1.0" encoding="UTF-8"?>
<response status="Not Found">
   <errorcode>500</errorcode>
   <message>some message</message>
   <description>some description</description>
</response>

1 个答案:

答案 0 :(得分:0)

类似的东西

use XML::LibXML;

my $doc = XML::LibXML->createDocument( "1.0", "UTF-8" );
my $root = $doc->createElement("response");
$root->setAttribute('status'=> 'Not Found');

my %tags = (
    errorcode => 500,
    message => 'some message',
    description => 'some description',
);

for my $name (keys %tags) {
    my $tag = $doc->createElement($name);
    my $value = $tags{$name};
    $tag->appendTextNode($value);
    $root->appendChild($tag);
}

$doc->setDocumentElement($root);
print $doc->toString(2); # <= XML indentation