Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- require "rexml/document"
- require "rubygems"
- require "builder"
- class Item
- attr_reader :code, :name, :quantity, :price
- def initialize(code, name, quantity, price)
- @code = code
- @name = name
- @quantity = quantity
- @price = price
- end
- def validate_item(items)
- items.each do |item|
- return false if item.code == self.code
- end
- true
- end
- end
- class Customer
- attr_reader :name, :street, :city, :zip, :country, :state
- def initialize(name, street, city, zip, country, state)
- @name = name
- @street = street
- @city = city
- @zip = zip
- @country = country
- @state = state
- end
- def validate_customer(customers)
- customers.each do |customer|
- return false if customer.name == self.name
- end
- true
- end
- end
- def load_xml(file)
- customers = []
- items_list = []
- File.open(file,"r") do |file|
- doc = REXML::Document.new(file)
- doc.root.elements.each do |order|
- address = order.elements["address[@type='billing']"]
- 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)
- customers << customer if customer.validate_customer(customers)
- #tady to je druhy zpusob jak pracovat s xml, radeji ukazu oba at to chapes :D
- doc.each_element('//orders//order//items//item') do |items|
- item = Item.new(items.attributes["code"],items.elements["name"].text, items.elements["quantity"].text, items.elements["price"].text)
- items_list << item if item.validate_item(items_list)
- end
- end
- end
- return customers, items_list
- end
- def print_xml(file,customers, items)
- File.open(file,"w+") do |file|
- xml = Builder::XmlMarkup.new({:target => file, :indent => 2})
- xml.instruct!
- xml.database do
- xml.customers do
- customers.each do |customer|
- xml.customer do
- xml.name(customer.name)
- xml.street(customer.street)
- xml.city(customer.city)
- xml.state(customer.state)
- xml.zip(customer.zip)
- xml.country(customer.country)
- end
- end
- end
- xml.items do
- items.each do |item|
- xml.item({:code => item.code}) do
- xml.name(item.name)
- xml.price(item.price)
- end
- end
- end
- end
- end
- end
- puts "Nacitam XML"
- customers, items = load_xml("orders.xml")
- puts "Zapisuju XML"
- print_xml("output.xml",customers, items)
Add Comment
Please, Sign In to add comment