This question already has an answer here:
- xml diff in ruby? [closed] 9 answers
What's the easiest way to see the difference between two xml files using?
I looked into Hpricot and Nokogiri but couldn't find any good comparison methods. I've also looked into unix tools like diffxml, but would rather use something in ruby.
Anybody got any ideas?
What about diff.rb ?
You export your two xml documents to arrays and get the diff with that library.
Try the equivalent-xml gem. It can tell you if two XML documents are semantically equivalent
I found that was easier to use the Java library XMLUnit than any native solution
require 'java'
require '/usr/share/java/xmlunit.jar'
java_import org.custommonkey.xmlunit.Diff
puts Diff.new("<a></a>", "<a/>").similar
puts Diff.new("<a/>", "<b/>").similar
Of course, this means you have to use JRuby instead of CRuby, but that wasn't a significant obstacle in my case.
Another option is to regularize your xml by round tripping it through xml-simple, and then doing an array diff on the lines of the output:
require 'rubygems'
require 'xmlsimple'
require 'diff'
def regularize(xml)
XmlSimple.xml_out(XmlSimple.xml_in(xml))
end
def diff_xml(a,b)
Diff.new(regularize(a).split("\n"), regularize(b).split("\n"))
end
puts diff_xml("<doc><a/></doc>", "<doc><a></a></doc>").diffs.empty?
puts diff_xml("<doc><a/></doc>", "<doc><b/></doc>").diffs.empty?
来源:https://stackoverflow.com/questions/1558613/diff-two-xml-doc-in-ruby