Comparing XML documents

T

Toby Rodwell

I'd like to check the equivalence of two XML documents. Searching this
forum I found some short and elegant code, but it considered docs
unequal if their elements were in a different order. Any
suggestions/advice? Thanks in advance.
 
M

Michael Fellinger

I'd like to check the equivalence of two XML documents. =C2=A0Searching t= his
forum I found some short and elegant code, but it considered docs
unequal if their elements were in a different order. =C2=A0Any
suggestions/advice? =C2=A0Thanks in advance.

Maybe using https://github.com/flavorjones/lorax


--=20
Michael Fellinger
CTO, The Rubyists, LLC
 
B

brabuhr

I'd like to check the equivalence of two XML documents. =A0Searching this
forum I found some short and elegant code, but it considered docs
unequal if their elements were in a different order. =A0Any
suggestions/advice? =A0Thanks in advance.

require 'active_support'
require 'active_support/xml_mini'
require 'active_support/core_ext/hash'

doc1 =3D Hash.from_xml <<END
<foo>
<bar>1</bar>
<bar>2</bar>
</foo>
END

doc2 =3D Hash.from_xml <<END
<foo>
<bar>1</bar>
<bar>2</bar>
</foo>
END

# assert_equal doc1, doc2
#=3D> pass

doc3 =3D Hash.from_xml <<END
<foo>
<bar>2</bar>
<bar>1</bar>
</foo>
END

# assert_equal doc1, doc3
#=3D> fail

def foo thing
case thing
when Hash
thing.each{|_, t| foo t}
when Array
thing.sort!
thing.each{|t| foo t}
end
end

# assert_equal doc1, foo(doc3)
#=3D> true
 
R

Robert Klemme

From an XML point of view documents with different child ordering are
not equivalent. So you will not be likely to find standard XML tools
that do the comparison - at least not without further adjusting (e.g.
ordering elements before feeding them to the comparison or converting
them to something else as were suggested.
require 'active_support'
require 'active_support/xml_mini'
require 'active_support/core_ext/hash'

doc1 = Hash.from_xml<<END
<foo>
<bar>1</bar>
<bar>2</bar>
</foo>
END

doc2 = Hash.from_xml<<END
<foo>
<bar>1</bar>
<bar>2</bar>
</foo>
END

# assert_equal doc1, doc2
#=> pass

doc3 = Hash.from_xml<<END
<foo>
<bar>2</bar>
<bar>1</bar>
</foo>
END

# assert_equal doc1, doc3
#=> fail

def foo thing
case thing
when Hash
thing.each{|_, t| foo t}
when Array
thing.sort!
thing.each{|t| foo t}

I would rather use

thing.sort.each{|t| foo t}

to avoid side effects from the test. Tests are generally considered
read only and if they have side effects you'll run into weird issues
that will be hard to hunt down.
end
end

# assert_equal doc1, foo(doc3)
#=> true

Kind regards

robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top