| 1 | package Data::XLSX::Parser::SharedStrings; | ||
| 2 | use strict; | ||
| 3 | use warnings; | ||
| 4 | |||
| 5 | use XML::Parser::Expat; | ||
| 6 | use Archive::Zip (); | ||
| 7 | use File::Temp; | ||
| 8 | use Carp; | ||
| 9 | |||
| 10 | sub new { | ||
| 11 | my ($class, $archive) = @_; | ||
| 12 | |||
| 13 | my $self = bless { | ||
| 14 | _data => [], | ||
| 15 | |||
| 16 | _is_string => 0, | ||
| 17 | _is_ph => 0, | ||
| 18 | _buf => '', | ||
| 19 | }, $class; | ||
| 20 | |||
| 21 | my $fh = File::Temp->new( SUFFIX => '.xml' ) or confess "couldn't create temporary file: $!"; | ||
| 22 | |||
| 23 | my $handle = $archive->shared_strings or return $self; | ||
| 24 | confess 'Failed to write temporary file: ', $fh->filename | ||
| 25 | unless $handle->extractToFileNamed($fh->filename) == Archive::Zip::AZ_OK; | ||
| 26 | |||
| 27 | my $parser = XML::Parser::Expat->new(Namespaces=>1); | ||
| 28 | $parser->setHandlers( | ||
| 29 | Start => sub { $self->_start(@_) }, | ||
| 30 | End => sub { $self->_end(@_) }, | ||
| 31 | Char => sub { $self->_char(@_) }, | ||
| 32 | ); | ||
| 33 | $parser->parse($fh); | ||
| 34 | |||
| 35 | $self; | ||
| 36 | } | ||
| 37 | |||
| 38 | sub count { | ||
| 39 | my ($self) = @_; | ||
| 40 | scalar @{ $self->{_data} }; | ||
| 41 | } | ||
| 42 | |||
| 43 | sub get { | ||
| 44 | my ($self, $index) = @_; | ||
| 45 | $self->{_data}->[$index]; | ||
| 46 | } | ||
| 47 | |||
| 48 | sub _start { | ||
| 49 | my ($self, $parser, $name, %attrs) = @_; | ||
| 50 | $self->{_is_string} = 1 if $name eq 'si'; | ||
| 51 | $self->{_is_ph} = 1 if $name eq 'rPh'; | ||
| 52 | } | ||
| 53 | |||
| 54 | sub _end { | ||
| 55 | my ($self, $parser, $name) = @_; | ||
| 56 | |||
| 57 | if ($name eq 'si') { | ||
| 58 | $self->{_is_string} = 0; | ||
| 59 | push @{ $self->{_data} }, $self->{_buf}; | ||
| 60 | $self->{_buf} = ''; | ||
| 61 | } | ||
| 62 | $self->{_is_ph} = 0 if $name eq 'rPh'; | ||
| 63 | } | ||
| 64 | |||
| 65 | sub _char { | ||
| 66 | my ($self, $parser, $data) = @_; | ||
| 67 | $self->{_buf} .= $data if $self->{_is_string} && !$self->{_is_ph}; | ||
| 68 | } | ||
| 69 | |||
| 70 | 1; | ||
| 71 | __END__ |