4 # Compare two XML files for structural and content equivalence. Used for
13 use XML::NamespaceSupport;
15 my $parser = XML::DOM::Parser->new;
16 my $d1 = $parser->parsefile($ARGV[0]);
17 my $d2 = $parser->parsefile($ARGV[1]);
18 my $nsup1 = XML::NamespaceSupport->new;
19 my $nsup2 = XML::NamespaceSupport->new;
21 compare($d1, $d2, $nsup1, $nsup2);
24 my ($n1, $n2, $nsup1, $nsup2) = @_;
26 if ($n1->getNodeType != $n2->getNodeType) {
27 printf STDERR "Node types don't match (%u vs. %u)\n",
28 $n1->getNodeType, $n2->getNodeType;
35 if ($n1->getNodeType == XML::DOM::ELEMENT_NODE) {
36 process_namespaces($n1, $nsup1);
37 process_namespaces($n2, $nsup2);
40 my ($nsuri1, undef, $lname1) = $nsup1->process_element_name($n1->getNodeName);
41 my ($nsuri2, undef, $lname2) = $nsup2->process_element_name($n2->getNodeName);
43 # compare element names
44 unless ($nsuri1 eq $nsuri2 && $lname1 eq $lname2) {
45 print STDERR "$nsuri1/$lname1 != $nsuri2/$lname2\n";
50 my $attrs1 = $n1->getAttributes;
51 my $attrs2 = $n2->getAttributes;
53 # this will need some special care, since we ignore xmlns= attributes; defer
54 # to its own function so it's easier to do comparison both ways
55 compare_attr_list($attrs1, $attrs2, $nsup1, $nsup2) if (defined($attrs1));
56 compare_attr_list($attrs2, $attrs1, $nsup2, $nsup1) if (defined($attrs2));
58 # this element is ok, let's compare all children
59 my $c1 = $n1->getChildNodes;
60 my $c2 = $n2->getChildNodes;
62 if ($c1->getLength != $c2->getLength) {
63 print STDERR "$nsuri1/$lname1 has differing number of children\n";
66 for my $i (0..($c1->getLength-1)) {
67 compare($c1->item($i), $c2->item($i), $nsup1, $nsup2);
74 sub process_namespaces {
75 my ($node, $nsup) = @_;
77 my $attrs = $node->getAttributes;
78 return unless defined($attrs);
80 for my $attr ($attrs->getValues) {
81 my $name = $attr->getName;
82 if ($name =~ /^xmlns:(.*)$/) {
83 $nsup->declare_prefix($1, $attr->getValue);
88 sub compare_attr_list {
89 my ($attrs1, $attrs2, $nsup1, $nsup2) = @_;
91 for my $attr1 ($attrs1->getValues) {
92 my $name = $attr1->getName;
93 next if ($name =~ /^xmlns:(.*)$/);
95 my ($nsuri1, undef, $lname1) = $nsup1->process_attribute_name($attr1->getName);
97 if (!defined($attrs2)) {
98 # n2 has no attributes at all
99 print STDERR "Attribute $nsuri1/$lname1 exists on one side but not the other\n";
104 for my $attr2 ($attrs2->getValues) {
105 my ($nsuri2, undef, $lname2) = $nsup2->process_attribute_name($attr2->getName);
107 if ($nsuri1 eq $nsuri2 && $lname1 eq $lname2) {
108 $attr2_found = $attr2;
113 if (!defined($attr2_found)) {
114 print STDERR "Attribute $nsuri1/$lname1 exists on one side but not the other\n";
118 if ($attr1->getValue ne $attr2_found->getValue) {
119 print STDERR "Attribute $nsuri1/$lname1 has differing values\n";