Search code examples
rubyrexml

REXML: How to add the root element in a exiting but empty file?


I have an empty XML page I've called "users.xml". I'd like to be able to create all the content using REXML.

require "rexml/document"
include REXML  # so that we don't have to prefix everything with REXML::...

xmlfile = File.new("users.xml")
doc = Document.new(xmlfile)

//code to save root element here...

It looks to me that doc reads first the content of "users.xml", but changes that occurred in doc do not propagate back. How do I save changes to the file?


Solution

  • You open the file:

    doc = Document.new(xmlfile)
    

    but you never read it, or write it again.

    You need to use something like:

    xmlfile = File.read("users.xml")
    

    to read it, (which isn't a scalable way to do it, but that's an entirely different subject).

    After you convert it to a REXML document using doc = Document.new(xmlfile), you need to write it back out. You can use File.write or File.open with a block.