| 1 | package XML::Similarity; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | use Data::Dumper; | ||
| 6 | |||
| 7 | use XML::DOM; | ||
| 8 | use Algorithm::LCS; | ||
| 9 | |||
| 10 | sub new { | ||
| 11 | my $class = shift; | ||
| 12 | bless { | ||
| 13 | dom_x => new XML::DOM::Parser, | ||
| 14 | dom_y => new XML::DOM::Parser, | ||
| 15 | lcs => Algorithm::LCS->new, | ||
| 16 | } => $class; | ||
| 17 | } | ||
| 18 | |||
| 19 | sub _serialize_tree { | ||
| 20 | my $self = shift; | ||
| 21 | my $node = shift; | ||
| 22 | |||
| 23 | return unless $node->can('getTagName'); | ||
| 24 | |||
| 25 | my @serialization; | ||
| 26 | |||
| 27 | push @serialization, $node->getTagName; | ||
| 28 | for my $d ($node->getChildNodes) { | ||
| 29 | push @serialization, $self->_serialize_tree($d); | ||
| 30 | } | ||
| 31 | |||
| 32 | return @serialization; | ||
| 33 | } | ||
| 34 | |||
| 35 | sub calculate_similarity { | ||
| 36 | my $self = shift; | ||
| 37 | my $x = shift || return 0; | ||
| 38 | my $y = shift || return 0; | ||
| 39 | |||
| 40 | my $dom_x = $self->{dom_x}; | ||
| 41 | my $dom_y = $self->{dom_y}; | ||
| 42 | |||
| 43 | my $doc_x = $dom_x->parse($x); | ||
| 44 | my $doc_y = $dom_y->parse($y); | ||
| 45 | |||
| 46 | my @seq_x = $self->_serialize_tree($doc_x->getDocumentElement); | ||
| 47 | my @seq_y = $self->_serialize_tree($doc_y->getDocumentElement); | ||
| 48 | |||
| 49 | $doc_x->dispose; | ||
| 50 | $doc_y->dispose; | ||
| 51 | |||
| 52 | my @lcs = $self->{lcs}->LCS(\@seq_x, \@seq_y); | ||
| 53 | return 2 * (scalar @lcs) / (scalar(@seq_x) + scalar(@seq_y)); | ||
| 54 | } | ||
| 55 | |||
| 56 | 1; | ||
| 57 | __END__ |