perl 用 XML::Parser 解析 XML文件,访问哈希

本篇我们会看到 Perl 成为知名编程语言的关键特色--哈希 hash(2000年以前叫:关联数组)。

在Perl 中,可以使用各种模块和函数来解析 XML元素和属性。其中,最古老的模块是 XML::Parser,它提供了一组完整的XML解析和处理函数,可以解析XML文档中的元素和属性。

例如,下面是一个使用 XML::Parser 模块解析 XML元素和属性 的示例代码:

编写 xml_parser_tree.pl 如下

perl 复制代码
#!/usr/bin/perl
use 5.010;
use strict;
use warnings;
use utf8;
use XML::Parser;
use Data::Dumper;

if ($#ARGV != 0){
    die "You must specify a file.xml to parse";
}
my $file = shift @ARGV;
# Tree 风格比较难用,它的数据结构不符合标准的JSON.
my $p = XML::Parser->new(Style => 'Tree',
        Handlers => {Start => \&start, End => \&end_, Char => \&text});
my $tree = $p->parsefile($file) 
            or die "cannot read file.xml\n";
#print Dumper($tree);

my $f2 = $file .'.txt';
# 写入文件
open(my $fw, '>:encoding(UTF-8)', $f2) or die "cannot open file '$f2' $!";
my @array;
# 访问 hash
sub start { 
    my ($self, $tag, %attribs) = @_;
    if ($tag eq 'node'){
        push @array, $attribs{'TEXT'};
    }
}
sub end_ {
    my ($self, $tag) = @_;
}
sub text {
    my ($self, $text) = @_;
}
my $ln =0; # 行数
foreach my $txt (@array){
    print $fw $txt ."\n";
    $ln++;
}
close($fw);
print $ln;

运行 perl xml_parser_tree.pl your_test.xml

编写 xml_parser_subs.pl 如下

perl 复制代码
#!/usr/bin/perl
use 5.010;
use strict;
use warnings;
use utf8;
use XML::Parser;
#use Data::Dumper;

if ($#ARGV != 0){
    die "You must specify a file.xml to parse";
}
my $file = shift @ARGV;
# Subs 风格比较容易使用,它需要对应于标签名定义子程序
my $p = XML::Parser->new(Style => 'Subs',
        Handlers => {Char => \&text});
my $doc = $p->parsefile($file) 
            or die "cannot read file.xml\n";
say '$doc is a ', $doc;

my $f2 = $file .'.txt';
# 写入文件
open(my $fw, '>:encoding(UTF-8)', $f2) or die "cannot open file '$f2' $!";
my @array;
# 访问 hash
sub node { 
    my ($self, $tag, %attribs) = @_;
    push @array, $attribs{'TEXT'};
}
sub node_ {
    my ($self, $tag) = @_;
}
sub text {
    my ($self, $text) = @_;
}
my $ln =0; # 行数
foreach my $txt (@array){
    print $fw $txt ."\n";
    $ln++;
}
close($fw);
print $ln;

运行 perl xml_parser_subs.pl your_test.mm

参阅:XML::Parser - A perl module for parsing XML documents - metacpan.org

相关推荐
AI+程序员在路上11 小时前
XML介绍及常用c及c++库
xml·c语言·c++
炯哈哈16 小时前
【上位机——WPF】App.xml和Application类简介
xml·开发语言·c#·wpf·上位机
xrkhy21 小时前
java中XML的使用
xml·java·开发语言
huang_hai_an1 天前
jackson-dataformat-xml引入使用后,响应体全是xml
xml
张扬飞舞1 天前
IntelliJ IDEA打开项目后,目录和文件都不显示,只显示pom.xml,怎样可以再显示出来?
xml·java·intellij-idea
search72 天前
配置文件介绍xml、json
xml·json
SoFlu软件机器人3 天前
Java 框架配置自动化:告别冗长的 XML 与 YAML 文件
xml·java·自动化
AI+程序员在路上4 天前
Web Service及其实现技术(SOAP、REST、XML-RPC)介绍
xml·rpc·web
DragonnAi4 天前
【目标检测标签转换工具】YOLO 格式与 Pascal VOC XML 格式的互转详解(含完整代码)
xml·yolo·目标检测
小赵面校招4 天前
SpringBoot整合MyBatis-Plus:零XML实现高效CRUD
xml·spring boot·mybatis