Copyright ©

Ruby on Rails 2.1 and XML - RXML

previous next


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


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.

Please check the following link on XML Builder.

previous next

Copyright ©