Compare two XML strings as hashes

Posted About 12 years ago. Visible to the public.

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
Last edit
About 10 years ago
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2012-03-02 11:41)