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>
Run Code Online (Sandbox Code Playgroud)
我需要根据所选的实体名称解析文件,并按照提到的顺序检索所有表.我如何在Perl中执行此操作以及应使用哪个模块?
我最喜欢在Perl中解析XML的模块是XML::Twig(教程).
代码示例:
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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2571 次 |
| 最近记录: |