Builder::XmlMarkup allows you to create XML markup by calling methods that correspond to XML tags. Most methods can take a string as a value (for tag content) or a hash of attributes. If a block is provided, the method is treated as an opening tag, and the content inside the block is treated as nested markup.
Key Behaviors
- Automatic Escaping: Special XML characters like
<, >, and & are automatically converted to <, >, and &. - Namespaces: You can create namespaced tags by passing a symbol as the first argument. For example,
xml.SOAP :Envelope produces <SOAP:Envelope>. - Tag Names with Special Characters: For tags that use characters not allowed in Ruby identifiers, use the
tag! method. - Text Insertion: To insert raw text without enclosing it in tags, use the
text! method. - Block Semantics: In recent versions, markup methods inside a block must be explicitly called on the builder object (or the object passed into the block) to avoid ambiguity. Use the block argument to make this cleaner.
Example Usage
xml = Builder::XmlMarkup.new
# Simple tags
xml.em("emphasized") # => <em>emphasized</em>
xml.a("A Link", "href"=>"http://example.org") # => <a href="http://example.org">A Link</a>
# Nested tags with blocks
xml.div {
xml.p("paragraph")
}
# => <div><p>paragraph</p></div>
# Using the block argument (recommended)
xml.div do |xml|
xml.strong("bold")
end
# => <div><strong>bold</strong></div>
# Namespaces
xml.SOAP :Envelope do |xml|
xml.Body
end
# => <SOAP:Envelope><Body></Body></SOAP:Envelope>
# Handling special characters
xml.tag!("SOAP:Envelope", "attr" => "val")
# => <SOAP:Envelope attr="val"></SOAP:Envelope>
require 'builder/xmlmarkup'
xml = Builder::XmlMarkup.new
xml.div {
xml.p("Hello World")
}