Skip to content

Instantly share code, notes, and snippets.

@scarver2
Created July 14, 2014 13:24
Show Gist options
  • Save scarver2/de4e760d614d9aa23629 to your computer and use it in GitHub Desktop.
Save scarver2/de4e760d614d9aa23629 to your computer and use it in GitHub Desktop.
Nokogiri XML builder with attributes and no xml declaration
require 'nokogiri'
def common_code_for_element_recipients(numbers)
xml = Nokogiri::XML::Builder.new
xml.recipients do
numbers.each do |number|
if number.is_a? Hash
xml.recipient(uid: number[:uid]) { xml.text number[:uid] }
else
xml.recipient number
end
end
end
xml.doc.root.to_xml
end
puts common_code_for_element_recipients([{uid: '123456789'}, '987654321'])
def common_code_for_element_recipients(numbers)
recipients_body_xml = '<recipients>'
numbers.each do |number|
# start the XML block
recipients_body_xml += "\n <recipient"
# individual numbers and (optional) UIDs
if number.is_a? Hash
recipients_body_xml += " uid=\"#{number[:uid]}\""
number = number[:number]
end
recipients_body_xml += ">#{number}</recipient>"
end
# close XML block
recipients_body_xml += "\n </recipients>"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment