Comparing 2 xml files

I am trying to compare 2 xml files,

require ‘equivalent-xml’
require ‘rspec/matchers’
class CompareXML

node_1 =
Nokogiri::XML::Document.parse(File.open(‘C:\xml_compare\tgt_print_1.xml’))
node_2 =
Nokogiri::XML::Document.parse(File.open(‘C:\xml_compare\tgt_print_2.xml’))

expect(node_1).to be_equivalent_to(node_2).respecting_element_order
expect(node_1).to
be_equivalent_to(node_2).with_whitespace_inexpect(node_1).to
be_equivalent_to(node_2)
expect(node_1).to
be_equivalent_to(node_2).respecting_element_order.with_whitespace_intact

end

also tried
EquivalentXml.equivalent?(node_1, node_2, opts = {:element_order =>
false, :normalize_whitespace => true}) { |n1, n2, result|
unless n1==n2
puts n1
puts n2

}

but both solutions are not working . Kindly advice.

Hello,

I’d be interested in the purpose of your program? RSpec is a test
framework, so perhaps you are testing your own program?

What exactly isn’t working? Do you mean the program has an error, or the
output does not meet your expectations? Is the XML valid? Are you sure
the XML is valid?


require ‘equivalent-xml’

xml1 = “”
xml2 = " "

result = EquivalentXml.equivalent?(xml1, xml2) # => true

puts result

This is a very simple example, using the default options. See if you can
get this to run.

Thanks for the reply Joe!!
I need to compare both the files including the xml structure and
content. and output the differences ,

now I tried something like below ,
app = Time.now.strftime("%m_%d_%Y_%H_%S")
output = File.open(“c:/files/xmlcomp_#{app}.txt”, ‘w’)

EquivalentXml.equivalent?(node_1, node_2, opts = {:element_order =>
false, :normalize_whitespace => true}) { |n1, n2, result|
unless n1.text == n2.text
output << “#{n1.text} :—DOES NOT MATCH–: #{n2.text} \n\n”
puts “#{n1.text} :—DOES NOT MATCH–: #{n2.text} \n\n”
end
}

but this only does the text and not the entire file.

Hello Surdarshan,
I recommend that you start with some small test cases to answer the
question, What are the options doing? What are the variables in the code
block doing?

In your case, in particular, why are you setting element_order to false?


require ‘equivalent-xml’

xml1 = “”
xml2 = " "

result = EquivalentXml.equivalent?(xml1, xml2) do |n1, n2, res|
puts n1
puts n2
puts “res: #{res}”
puts “–”
puts n1.class.name
puts res.class.name
puts “–”
end

Is this what you expected?

As you can see, the XML structure is going to be very important. Also,
the output will be important, what do you want to do after you’ve
compared the files?