dimanche 26 avril 2015

How to convert partial XML to hash in Ruby


I have a string which has plain text and extra spaces and carriage returns then XML-like tags followed by XML tags:

String = "hi there.

<SET-TOPIC> INITIATE </SET-TOPIC>

<SETPROFILE>
   <KEY>name</KEY>
   <VALUE>Joe</VALUE>
</SETPROFILE>

 <SETPROFILE>
   <KEY>email</KEY>
   <VALUE>Email@hi.com</VALUE>
</SETPROFILE>

<GET-RELATIONS>
  <COLLECTION>goals</COLLECTION>
  <VALUE>walk upstairs</VALUE>
</GET-RELATIONS>
So what do you think?

Is it true?
 "

I want to parse this similar to use Nori or Nokogiri or Ox where they convert XML to a hash.

My goal is to be able to easily pull out the top level tags as keys and then know all the elements, something like:

Keys = ['SETPROFILE', 'SETPROFILE', 'SET-TOPIC', 'GET-OBJECT']

Values[0] = [{name => Joe}, {email => email@hi.com}]
Values[3] = [{collection => goals}, {value => walk up}]

I have seen several functions like that for true XML but all of mine are partial.

I started going down this line of thinking:

parsed = doc.search('*').each_with_object({}) do |n, h| 
  (h[n.name] ||= []) << n.text 
end


Aucun commentaire:

Enregistrer un commentaire