Ruby on Rails 2.1 - XML - RXML



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

  • Builder::XmlMarkup − This Generates XML markup notation.

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

Builder::XmlMarkup

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.

Example

xm.em("emphasized")             
# => <em>emphasized</em>
xm.em { xmm.b("emp & bold") }   
# => <em><b>emph &amp; bold</b></em>
xm.a("A Link", "href"=>"http://onestepback.org")
# => <a href="http://onestepback.org">A Link</a>
xm.div { br }                    
# => <div><br/></div>
xm.target("name"=>"compile", "option"=>"fast")
# => <target option="fast" name="compile"\>
# NOTE: order of attributes is not specified.
xm.instruct!                   
# <?xml version="1.0" encoding="UTF-8"?>
xm.html {                      # <html>
   xm.head {                    #   <head>
      xm.title("History")        
      #  <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>

Builder::XmlEvents

This class 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 the XmlMarkup objects, except that a series of events are generated and passed to a handler rather than generating character-based markup.

Example

xe = Builder::XmlEvents.new(hander)
xe.title("HI")    
# 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.

rails-quick-guide.htm
Advertisements