Diff two XML doc in Ruby? [duplicate]

走远了吗. 提交于 2019-11-28 11:31:47

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?
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!