Cover by Leonard Richardson, Lucas Carlson

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

11.9. Creating and Modifying XML Documents

Problem

You want to modify an XML document, or create a new one from scratch.

Solution

To create an XML document from scratch, just start with an empty Document object.

	require 'rexml/document'
	require
	doc = REXML::Document.new

To add a new element to an existing document, pass its name and any attributes into its parent's add_element method. You don't have to create the Element objects yourself.

	meeting = doc.add_element 'meeting'
	meeting_start = Time.local(2006, 10, 31, 13)
	meeting.add_element('time', { 'from' => meeting_start,
	                              'to' => meeting_start + 3600 })

	doc.children[0]                                 # => <meeting> … </>
	doc.children[0].children[0]
	# => "<time from='Tue Oct 31 13:00:00 EST 2006'
	#      to='Tue Oct 31 14:00:00 EST 2006'/>"

	doc.write($stdout, 1)
	# <meeting>
	#  <time from='Tue Oct 31 13:00:00 EST 2006'
	#        to='Tue Oct 31 14:00:00 EST 2006'/>
	# </meeting>
	doc.children[0]                                 # => <?xml … ?>
	doc.children[1]                                 # => <meeting> … </>

To append a text node to the contents of an element, use the add_text method. This code adds an <agenda> element to the <meeting> element, and gives it two different text nodes:

	agenda = meeting.add_element 'agenda'
	doc.children[1].children[1]               # => <agenda/>

	agenda. add_text "Nothing of importance will be decided." agenda.add_text " The same tired ideas will be rehashed yet again." doc.children[1].children[1] # => <agenda> … </> doc.write($stdout, 1) # <meeting> # <time from='Tue Oct 31 13:00:00 EST 2006' # to='Tue Oct 31 14:00:00 EST 2006'/> ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required