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 money motivation

Opscomplete powered by makandra brand

Save money by migrating from AWS to our fully managed hosting in Germany.

  • Trusted by over 100 customers
  • Ready to use with Ruby, Node.js, PHP
  • Proactive management by operations experts
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)