Skip to content

Instantly share code, notes, and snippets.

@chrisbodhi
Last active August 29, 2015 14:15
Show Gist options
  • Save chrisbodhi/0a5a090d986daa0461b2 to your computer and use it in GitHub Desktop.
Save chrisbodhi/0a5a090d986daa0461b2 to your computer and use it in GitHub Desktop.
Add to an XML File
def update_xml_file(string_to_add, file)
# Ready a formatted string and XML'ify it
new_xml = Nokogiri::XML::DocumentFragment.parse(string_to_add)
# Open the XML file to which we add
@xml_file = Nokogiri::XML(File.read(file))
# Find the last instance of the `here` node
@insertion_point = @xml_file.css('here').last
# Stick the XML'ified string after the last 'here' node
@insertion_point.add_next_sibling(new_xml)
# Save it all
File.open(file, 'w') { |f| f.write(@xml_file.to_xml) }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment