Read the file into an in-memory XML document, modify the document as needed, then serialize the document back into the original file:
filename = 'exam.xml'xml = File.read(filename)doc = Nokogiri::XML(xml)# ... make changes to doc ...File.write(filename, doc.to_xml)