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 web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
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)