use XML::Simple;
require "files/camelid_links.pl";
my 蕀elid_links = get_camelid_data();
my $xsimple = XML::Simple->new();
print $xsimple->XMLout(\蕀elid_links,
noattr => 1,
xmldecl => '
这数据到文档的任务的条件要求暴露了XML::Simple的一个弱点:它没有答应我们决定hash里的哪个key应该作为元素返回和哪个key该作为属性返回。上面例子的输出虽然接近我们的输出要求但还远远不够。对于那些更喜欢将XML文档内容直接作为Perl数据结构操作,而且需要在输出方面做更细微控制的案例,XML::Simple和XML::Writer配合得很好。 如下例子说明了如何使用XML::Write来符合我们的输出要求。
use XML::Writer;
require "files/camelid_links.pl";
my 蕀elid_links = get_camelid_data();
my $writer = XML::Writer->new();
$writer->xmlDecl();
$writer->startTag('html');
$writer->startTag('body');
foreach my $item ( keys (蕀elid_links) ) {
$writer->startTag('a', 'href' => $camelid_links{$item}->{url});
$writer->characters($camelid_links{$item}->{description});
$writer->endTag('a');
}
$writer->endTag('body');
$writer->endTag('html');
$writer->end();
use XML::Parser;
use XML::SimpleObject;
my $file = 'files/camelids.xml';
my $parser = XML::Parser->new(ErrorContext => 2, Style => "Tree");
my $xso = XML::SimpleObject->new( $parser->parsefile($file) );
foreach my $species ($xso->child('camelids')->children('species')) {
print $species->child('common-name')->{VALUE};
print ' (' . $species->attribute('name') . ') ';
print $species->child('conservation')->attribute('status');
print "\n";
}
use XML::TreeBuilder;
my $file = 'files/camelids.xml';
my $tree = XML::TreeBuilder->new();
$tree->parse_file($file);
foreach my $species ($tree->find_by_tag_name('species')){
print $species->find_by_tag_name('common-name')->as_text;
print ' (' . $species->attr_get_i('name') . ') ';
print $species->find_by_tag_name('conservation')->attr_get_i('status');
print "\n";
}
use XML::Element;
require "files/camelid_links.pl";
my 蕀elid_links = get_camelid_data();
my $root = XML::Element->new('html');
my $body = XML::Element->new('body');
my $xml_pi = XML::Element->new('~pi', text => 'xml version="1.0"');
$root->push_content($body);
foreach my $item ( keys (蕀elid_links) ) {
my $link = XML::Element->new('a', 'href' => $camelid_links{$item}->{url});
$link->push_content($camelid_links{$item}->{description});
$body->push_content($link);
}
print $xml_pi->as_XML;
print $root->as_XML();
评论加载中…
![]() |