加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

perl XML::Parser

发布时间:2020-12-15 21:01:18 所属栏目:大数据 来源:网络整理
导读:使用Tree Style来解析xml文件 操作文件: [root@dou xml]# cat sample1 FORECAST ? OUTLOOK ??? Partly Cloudy ? /OUTLOOK ? TEMPERATURE TYPE="MAX" DEGREES="C"12/TEMPERATURE ? TEMPERATURE TYPE="MIN" DEGREES="C"6/TEMPERATURE /FORECAST ? XML::Parser

使用Tree Style来解析xml文件

操作文件:

[root@dou xml]# cat sample1
<FORECAST>
? <OUTLOOK>
??? Partly Cloudy
? </OUTLOOK>
? <TEMPERATURE TYPE="MAX" DEGREES="C">12</TEMPERATURE>
? <TEMPERATURE TYPE="MIN" DEGREES="C">6</TEMPERATURE>
</FORECAST>
?

XML::Parser中的Tree Style将xml文件内容转化为perl的数据结构如下:

[root@dou xml]# cat ch.pl
#!/usr/bin/perl -w
use strict;
use XML::Parser;
use Data::Dumper;

my $file = "sample1";
my $p = XML::Parser->new(Style => 'Tree');
my $doc = $p->parsefile($file);
print Dumper($doc);
[root@dou xml]# perl ch.pl
$VAR1 = [
????????? 'FORECAST',
????????? [
??????????? {},
??????????? 0,
??????????? '
? ',
??????????? 'OUTLOOK',
??????????? [
????????????? {},
????????????? 0,
????????????? '
??? Partly Cloudy
? '
??????????? ],
??????????? 'TEMPERATURE',
??????????? [
????????????? {
??????????????? 'TYPE' => 'MAX',
??????????????? 'DEGREES' => 'C'
????????????? },
????????????? '12'
??????????? ],
??????????? [
????????????? {
??????????????? 'TYPE' => 'MIN',
????????????? '6'
??????????? ],
??????????? '
'
????????? ]
??????? ];
[root@dou xml]#
?

转换原理参照:http://search.cpan.org/~msergeant/XML-Parser-2.36/Parser.pm中的Style的Tree。

Tree

Parse will return a parse tree for the document. Each node in the tree takes the form of a tag,content pair. Text nodes are represented with a pseudo-tag of "0" and the string that is their content. For elements,the content is an array reference. The first item in the array is a (possibly empty) hash reference containing attributes. The remainder of the array is a sequence of tag-content pairs representing the content of the element.

基本上就是 element [匿名数组]一次类推下去,涉及到嵌套。

脚本运行结果如下:

[root@dou xml]# perl sample2.pl sample1 Outlook: Partly Cloudy MAX:12 C MIN:6 C ?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读