XML结构如下:
<Entities>
<Entity>
<EntityName>.... </EntityName>
<EntityType>.... </EntityType>
<Tables>
<DataTables>
<DataTable>1</DataTable>
<DataTable>2</DataTable>
<DataTable>3</DataTable>
<DataTable>4</DataTable>
</DataTables>
<OtherTables>
<OtherTable>5</OtherTable>
<OtherTable>6</OtherTable>
</OtherTables>
</Tables>
</Entity>
.
.
.
</Entities>
我需要根据所选的实体名称解析文件,并专门按照提到的顺序检索所有表。我如何在 Perl 中执行此操作以及应该使用哪个模块?
我最喜欢的 Perl 中解析 XML 的模块是XML::Twig http://p3rl.org/XML::Twig (tutorial http://www.effectiveperlprogramming.com/2010/03/process-xml-data-with-xmltwig/).
代码示例:
use XML::Twig;
my $twig = XML::Twig->new(
twig_handlers => {
#calls the get_tables method for each Entity element
Entity => sub {get_tables($_);},
},
pretty_print => 'indented', # output will be nicely formatted
empty_tags => 'html', # outputs <empty_tag />
keep_encoding => 1,
);
$twig->parsefile(xml-file);
$twig->flush;
sub get_tables {
my $entity = shift;
#Retrieves the sub-elements of DataTables
my @data_tables = $entity->first_child("Tables")->children("DataTables");
#Do stuff with the DataTables
#Retrieves the sub-elements of OtherTables
my @other_tables = $entity->first_child("Tables")->children("OtherTables");
#Do stuff with the OtherTables
#Flushes the XML element from memory
$entity->purge;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)