Guest User

Untitled

a guest
Apr 21st, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.49 KB | None | 0 0
  1. require "rexml/document"
  2. require "rubygems"
  3. require "builder"
  4. class Item
  5. attr_reader :code, :name, :quantity, :price
  6. def initialize(code, name, quantity, price)
  7. @code = code
  8. @name = name
  9. @quantity = quantity
  10. @price = price
  11. end
  12.  
  13. def validate_item(items)
  14. items.each do |item|
  15. return false if item.code == self.code
  16. end
  17. true
  18. end
  19. end
  20.  
  21. class Customer
  22. attr_reader :name, :street, :city, :zip, :country, :state
  23. def initialize(name, street, city, zip, country, state)
  24. @name = name
  25. @street = street
  26. @city = city
  27. @zip = zip
  28. @country = country
  29. @state = state
  30. end
  31. def validate_customer(customers)
  32. customers.each do |customer|
  33. return false if customer.name == self.name
  34. end
  35. true
  36. end
  37. end
  38.  
  39. def load_xml(file)
  40. customers = []
  41. items_list = []
  42. File.open(file,"r") do |file|
  43. doc = REXML::Document.new(file)
  44. doc.root.elements.each do |order|
  45. address = order.elements["address[@type='billing']"]
  46. customer = Customer.new(address.elements["name"].text, address.elements["street"].text, address.elements["city"].text, address.elements["zip"].text, address.elements["country"].text, address.elements["state"].text)
  47. customers << customer if customer.validate_customer(customers)
  48. #tady to je druhy zpusob jak pracovat s xml, radeji ukazu oba at to chapes :D
  49. doc.each_element('//orders//order//items//item') do |items|
  50. item = Item.new(items.attributes["code"],items.elements["name"].text, items.elements["quantity"].text, items.elements["price"].text)
  51. items_list << item if item.validate_item(items_list)
  52. end
  53. end
  54. end
  55. return customers, items_list
  56. end
  57.  
  58. def print_xml(file,customers, items)
  59. File.open(file,"w+") do |file|
  60. xml = Builder::XmlMarkup.new({:target => file, :indent => 2})
  61. xml.instruct!
  62. xml.database do
  63. xml.customers do
  64. customers.each do |customer|
  65. xml.customer do
  66. xml.name(customer.name)
  67. xml.street(customer.street)
  68. xml.city(customer.city)
  69. xml.state(customer.state)
  70. xml.zip(customer.zip)
  71. xml.country(customer.country)
  72. end
  73. end
  74. end
  75. xml.items do
  76. items.each do |item|
  77. xml.item({:code => item.code}) do
  78. xml.name(item.name)
  79. xml.price(item.price)
  80. end
  81. end
  82. end
  83. end
  84. end
  85. end
  86.  
  87.  
  88. puts "Nacitam XML"
  89. customers, items = load_xml("orders.xml")
  90. puts "Zapisuju XML"
  91. print_xml("output.xml",customers, items)
Add Comment
Please, Sign In to add comment