Ruby on Rails 2.1 - XML - RXML


Rails provide two classes to create XML markup and data structures.

  • Builder::XmlMarkup: This Generates XML markup notiation.

  • Builder::XmlEvents: This Generates XML events (i.e. SAX-like)


This class can be used to create XML markup easily. All methods sent to an XmlMarkup object will be translated to the equivalent XML markup. Any method with a block will be treated as an XML markup tag with nested markup in the block.

Assuming xm is an XmlMarkup object, we have picked up one example from Rails standard documentation site. Here commented part has been generated from the corresponding Rails statement.


# => <em>emphasized</em>
xm.em { xmm.b("emp & bold") }   
# => <em><b>emph &amp; bold</b></em>
xm.a("A Link", "href"=>"")
# => <a href="">A Link</a>
xm.div { br }                    
# => <div><br/></div>"name"=>"compile", "option"=>"fast")
# => <target option="fast" name="compile"\>
# NOTE: order of attributes is not specified.
# <?xml version="1.0" encoding="UTF-8"?>
xm.html {                      # <html>
   xm.head {                    #   <head>
      #  <title>History</title>
   }                            #   </head>
   xm.body {                    #   <body>
      xm.comment! "HI"           #   <!-- HI -->
      xm.h1("Header")            #   <h1>Header</h1>
      xm.p("paragraph")          #   <p>paragraph</p>
   }                            #   </body>
}                              #   </html>


This calss can be used to create a series of SAX-like XML events (e.g. start_tag, end_tag) from the markup code.

XmlEvent objects are used in a way similar to XmlMarkup objects, except that a series of events are generated and passed to a handler rather than generating character-based markup.


xe =
# This sends start_tag/end_tag/text messages to the handler.

XML Event Handler

The handler object must expect the following events.

  • start_tag(tag, attrs): Announces that a new tag has been found. tag is the name of the tag and attrs is a hash of attributes for the tag.

  • end_tag(tag): Announces that an end tag for tag has been found.

  • text(text): Announces that a string of characters (text) has been found. A series of characters may be broken up into more than one text call, so the client cannot assume that a single callback contains all the text data.

Please check the following link on XML Builder.