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


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

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

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

    编写 xml_parser_tree.pl  如下

    1. #!/usr/bin/perl
    2. use 5.010;
    3. use strict;
    4. use warnings;
    5. use utf8;
    6. use XML::Parser;
    7. use Data::Dumper;
    8. if ($#ARGV != 0){
    9. die "You must specify a file.xml to parse";
    10. }
    11. my $file = shift @ARGV;
    12. # Tree 风格比较难用,它的数据结构不符合标准的JSON.
    13. my $p = XML::Parser->new(Style => 'Tree',
    14. Handlers => {Start => \&start, End => \&end_, Char => \&text});
    15. my $tree = $p->parsefile($file)
    16. or die "cannot read file.xml\n";
    17. #print Dumper($tree);
    18. my $f2 = $file .'.txt';
    19. # 写入文件
    20. open(my $fw, '>:encoding(UTF-8)', $f2) or die "cannot open file '$f2' $!";
    21. my @array;
    22. # 访问 hash
    23. sub start {
    24. my ($self, $tag, %attribs) = @_;
    25. if ($tag eq 'node'){
    26. push @array, $attribs{'TEXT'};
    27. }
    28. }
    29. sub end_ {
    30. my ($self, $tag) = @_;
    31. }
    32. sub text {
    33. my ($self, $text) = @_;
    34. }
    35. my $ln =0; # 行数
    36. foreach my $txt (@array){
    37. print $fw $txt ."\n";
    38. $ln++;
    39. }
    40. close($fw);
    41. print $ln;

    运行 perl xml_parser_tree.pl your_test.xml

    编写  xml_parser_subs.pl  如下

    1. #!/usr/bin/perl
    2. use 5.010;
    3. use strict;
    4. use warnings;
    5. use utf8;
    6. use XML::Parser;
    7. #use Data::Dumper;
    8. if ($#ARGV != 0){
    9. die "You must specify a file.xml to parse";
    10. }
    11. my $file = shift @ARGV;
    12. # Subs 风格比较容易使用,它需要对应于标签名定义子程序
    13. my $p = XML::Parser->new(Style => 'Subs',
    14. Handlers => {Char => \&text});
    15. my $doc = $p->parsefile($file)
    16. or die "cannot read file.xml\n";
    17. say '$doc is a ', $doc;
    18. my $f2 = $file .'.txt';
    19. # 写入文件
    20. open(my $fw, '>:encoding(UTF-8)', $f2) or die "cannot open file '$f2' $!";
    21. my @array;
    22. # 访问 hash
    23. sub node {
    24. my ($self, $tag, %attribs) = @_;
    25. push @array, $attribs{'TEXT'};
    26. }
    27. sub node_ {
    28. my ($self, $tag) = @_;
    29. }
    30. sub text {
    31. my ($self, $text) = @_;
    32. }
    33. my $ln =0; # 行数
    34. foreach my $txt (@array){
    35. print $fw $txt ."\n";
    36. $ln++;
    37. }
    38. close($fw);
    39. print $ln;

    运行 perl xml_parser_subs.pl your_test.mm

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

  • 相关阅读:
    EMQX 集群节点数据转发
    网络安全基础技术扫盲篇 — 名词解释之“数据包“
    大数据运维一些常见批量操作命令
    使用VisualStudio生成类图结构图for高效阅读代码
    万向区块链小课堂:超短文梳理区块链层级,字字珠玑
    C语言经典面试题目(十八)
    Spring源码------IOC容器初始化过程
    socket编程详解(一)——服务器端
    网络安全(黑客)自学
    相约黄浦江畔,汇聚AI与边缘计算的力量
  • 原文地址:https://blog.csdn.net/belldeep/article/details/136759388