当前位置: 首页 > news >正文

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

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

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

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

编写 xml_parser_tree.pl  如下

#!/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  如下

#!/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

http://www.lryc.cn/news/319110.html

相关文章:

  • MATLAB中的矩阵和数组,它们之间有什么区别?
  • python爬虫实战——抖音
  • Day1-力扣刷题学习打卡
  • C语言的位操作与位字段
  • 应用实战|从头开始开发记账本1:如何获取BaaS服务
  • el-form v-for循环列表的表单如何校验
  • 笔记:《NCT全国青少年编程能力等级测试教程Python语言编程三级》
  • 地平线旭日x3派部署yolov5--全流程
  • 【Golang星辰图】Go语言云计算SDK全攻略:深入Go云存储SDK实践
  • 深入理解TCP:序列号、确认号和自动ACK的艺术
  • 家电工厂5G智能制造数字孪生可视化平台,推进家电工业数字化转型
  • ctf_show笔记篇(web入门---代码审计)
  • c语言的字符串函数详解
  • HarmonyOS NEXT应用开发—折叠屏音乐播放器方案
  • Java项目:55 springboot基于SpringBoot的在线视频教育平台的设计与实现015
  • 说下你对TCP以及TCP三次握手四次挥手的理解?
  • wsl-oracle 安装 omlutils
  • Python类属性和对象属性大揭秘!
  • 北斗卫星在桥隧坡安全监测领域的应用及前景展望
  • 如何通过堡垒机JumpServer使用VisualCode 连接服务器进行开发
  • 【Linux】进程优先级
  • Fair Data Exchange:区块链实现的原子式公平数据交换
  • 详解优雅版线程池ThreadPoolTaskExecutor和ThreadPoolTaskExecutor的装饰器
  • Vue3+TS+Vite 找不到模块“@/components/xxx/xxx”或其相应的类型声明
  • Vue3-响应式基础:单文件和组合式文件
  • DVWA-File Upload文件上传
  • python之word操作
  • Linux下新增有root权限的用户
  • RPC通信原理(一)
  • 修改/etc/resolve.conf重启NetworkManager之后自动还原