Compare two XML strings as hashes

Let's say you have two XML strings that are ordered differently but you don't care about the order of attributes inside containers:

a = '<?xml version="1.0" encoding="UTF-8"?><Authenticate><User>batman</User><Password>secret</Password></Authenticate>'
b = '<?xml version="1.0" encoding="UTF-8"?><Authenticate><Password>secret</Password><User>batman</User></Authenticate>'

Working with plain string comparison is not helpful, of course:

a == b
=> false

Instead, you can use the Nori Show archive.org snapshot gem to convert your XML into a hash:

xml_parser = Nori.new

xml_parser.parse(a)
=> {:authenticate=>{:user=>"batman", :password=>"secret"}}

xml_parser.parse(a) == xml_parser.parse(b)
=> true

Note: order in XML can be important (e.g. XHTML). For cases where it's not, you can compare like this.

Arne Hartherz About 12 years ago