Guest User

Untitled

a guest
Jan 22nd, 2018
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.32 KB | None | 0 0
  1. module XmlConvertor
  2. require 'ox'
  3.  
  4. # Class for parsing the XML to Hash Objects and backwards.
  5. class XMLtoHash
  6.  
  7. # Convert XML input to Hash object for easy handeling within the application
  8. # @param xml [String] The XML formated String you want to convert from
  9. # @return [Hash] XML input in a Hash object
  10. def XMLtoHash(xml)
  11. hash = Ox.load(xml, mode: :hash)
  12. return hash
  13. end
  14.  
  15. # Convert Hash to valid XML, The hash will be converted recusive
  16. # @param hash [Hash] Hash object used as input
  17. # @param parent [Object] Parent element for sub element from hash. (used for recursion)
  18. # @return [String] XML valid string
  19. def HashtoXML(hash, parent = nil)
  20. # Check if parent is set else create the start element
  21. if parent.nil?
  22. parent = Ox::Document.new(:version => '1.0')
  23. end
  24.  
  25. # Start looping through the hash elements and create elements for the keys
  26. # assign the new element to the parent or asssing a value to the element
  27. hash.each do |key, value|
  28. if value.is_a?(Hash)
  29. key = Ox::Element.new(key)
  30. parent << key
  31. self.HashtoXML(value, key)
  32. else
  33. key = Ox::Element.new(key)
  34. parent << key
  35. key << value
  36. end
  37. end
  38.  
  39. return Ox.dump(parent)
  40. end
  41.  
  42. end
  43. end
Add Comment
Please, Sign In to add comment