require 'rexml/document' def valid_xml?(xml) begin REXML::Document.new(xml) rescue REXML::ParseException # Return nil if an exception is thrown end end good_xml = %{ <groceries> <bread>W</bread> <bread>Q</bread> </groceries>} doc = valid_xml?(good_xml) p doc.root.elements[1] # => <bread> ... </>