REXML: Proccessing XML in Ruby, Page 3
Updating a Document with REXML
Now that you have learned how to access XML document elements with REXML, it's time to do some updates to the document using the REXML API. You will use the API to add a new guitar 'make', with one 'model' in it. Enter the following into a new file called 'REXMLUpdateTest.rb':
require "rexml/document" include REXML # so that we don't have to prefix everything with # REXML::... doc = Document.new File.new("guitars.xml") root = doc.root make = Element.new "make" make.attributes["name"] = "Gibson" model = Element.new "model" model.attributes["sn"] = "99999999" model.attributes["year"] = "2007" model.attributes["country"] = "USA" model.add_element "name" model.elements["name"].text = "SG" model.add_element "price" model.elements["price"].text = "1250.00" model.add_element "color" model.elements["color"].text = "Red" make.add_element model root.add_element make print doc
You began by getting the root element of the document, storing it in a variable 'root'. You then created your 'make' and 'model' elements. Note that you created both attributes and elements within the 'model' element. You then added the 'model' as a child element of 'make', and added 'make' to the document root. Running the script, you should see the following:
Click here for a larger image.
You now have added a new make to your guitar list, with a model in it.
This article took a look at the REXML library and showed how it can be used to process XML within your Ruby or Rails application. Like most things in Ruby and Rails, getting up and running with REXML is both simple and intuitive. REXML makes adding XML support to your application a breeze, with a quick learning curve. There are many more functions provided by REXML, so give it a good look and see what it has to offer you.
- Ruby: http://www.ruby-lang.org/en/
- Ruby on Rails: http://www.rubyonrails.org/
- REXML: http://www.germane-software.com/software/rexml/
- SilvaSoft, Inc. weblog: http://jroller.com/page/silvasoftinc
About the Author
Dominic Da Silva (http://www.dominicdasilva.com/) is the President of SilvaSoft, Inc., a software consulting company specializing in Java, Ruby, and .NET-based web and web services development. He has worked with Java since the year 2000 and is a Linux user from the 1.0 days. He is also Sun Certified for the Java 2 platform. Born on the beautiful Caribbean island of Trinidad and Tobago, he now makes his home in sunny Orlando, Florida.
Page 3 of 3