使用perl XML :: LibXML来如此缓慢地处理XML

前端之家收集整理的这篇文章主要介绍了使用perl XML :: LibXML来如此缓慢地处理XML前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
XML文件是这样的:

<?xml version="1.0" encoding="UTF-8"?>
<resource-data xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="resource-data.xsd">
  <class name="AP">
    <attributes>
      <resourceId>00 11 B5 1B 6D 20</resourceId>
      <lastModifyTime>20130107091545</lastModifyTime>
      <dcTime>20130107093019</dcTime>
      <attribute name="NMS_ID" value="DNMS" />
      <attribute name="IP_ADDR" value="10.11.141.111" />
      <attribute name="LABEL_DEV" value="00 11 B5 1B 6D 20" />
    </attributes>
        <attributes>
      <resourceId>00 11 B5 1B 6D 21</resourceId>
      <lastModifyTime>20130107091546</lastModifyTime>
      <dcTime>20130107093019</dcTime>
      <attribute name="NMS_ID" value="DNMS" />
      <attribute name="IP_ADDR" value="10.11.141.112" />
      <attribute name="LABEL_DEV" value="00 11 B5 1B 6D 21" />
    </attributes>
  </class>
</resource-data>

我的代码

#!/usr/bin/perl

use Encode;
use XML::LibXML;
use Data::Dumper;

$parser = new XML::LibXML;
$struct = $parser->parse_file("d:/AP_201301073100_1.xml");

my $file_data = "d:\\ap.txt";
open IN,">$file_data";

$rootel = $struct->getDocumentElement();
$elname = $rootel->getName();

@kids   = $rootel->getElementsByTagName('attributes');
foreach $child (@kids) {
  @atts = $child->getElementsByTagName('attribute');
  foreach $at (@atts) {
    $va = $at->getAttribute('value');
    print IN encode("gbk","$va\t");
  }
  print IN encode("gbk","\n");
}
close(IN);

我的问题是,如果XML文件只有80MB,那么程序将非常快,但是当XML文件大得多时,程序可能会非常慢.有人可以帮助我加快速度吗?

解决方法

另一种可能性是使用 XML::LibXML::Reader.它与SAX类似,但使用与XML :: LibXML相同的libxml库:

#!/usr/bin/perl
use warnings;
use strict;

use XML::LibXML::Reader;

my $reader = XML::LibXML::Reader->new(location => '1.xml');

open my $OUT,'>:encoding(gbk)','1.out';

while ($reader->read) {
    attr($reader) if 'attributes' eq $reader->name
                     and XML_READER_TYPE_ELEMENT == $reader->nodeType;
}

sub attr {
    my $reader = shift;
    my @kids;
  ATTRIBUTE:
    while ($reader->read) {
        my $name = $reader->name;
        last ATTRIBUTE if 'attributes' eq $name;
        next ATTRIBUTE if XML_READER_TYPE_END_ELEMENT == $reader->nodeType;
        push @kids,$reader->getAttribute('value')
            if 'attribute' eq $name;
    }
    print {$OUT} join("\t",@kids),"\n";
}

猜你在找的Perl相关文章