Read more

Compare two XML strings as hashes

Arne Hartherz
March 02, 2012Software engineer at makandra GmbH

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>'
Illustration online protection

Rails professionals since 2007

Our laser focus on a single technology has made us a leader in this space. Need help?

  • We build a solid first version of your product
  • We train your development team
  • We rescue your project in trouble
Read more Show archive.org snapshot

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.

Posted by Arne Hartherz to makandra dev (2012-03-02 12:41)