to_xml
- 1.0.0
- 1.1.6
- 1.2.6
- 2.0.3
- 2.1.0
- 2.2.1
- 2.3.8
- 3.0.0 (0)
- 3.0.9 (-10)
- 3.1.0 (38)
- 3.2.1 (0)
- 3.2.8 (0)
- 3.2.13 (0)
- 4.0.2 (-1)
- 4.1.8 (2)
- 4.2.1 (0)
- 4.2.7 (0)
- 4.2.9 (-4)
- 5.0.0.1 (0)
- 5.1.7 (0)
- 5.2.3 (0)
- 6.0.0 (0)
- 6.1.3.1 (0)
- 6.1.7.7 (0)
- 7.0.0 (0)
- 7.1.3.2 (-1)
- 7.1.3.4 (0)
- What's this?
to_xml(options = {})
public
Returns a string containing an XML representation of its receiver:
{"foo" => 1, "bar" => 2}.to_xml # => # <?xml version="1.0" encoding="UTF-8"?> # <hash> # <foo type="integer">1</foo> # <bar type="integer">2</bar> # </hash>
To do so, the method loops over the pairs and builds nodes that depend on the values. Given a pair key, value:
- If value is a hash there’s a recursive call with key as :root.
- If value is an array there’s a recursive call with key as :root, and key singularized as :children.
- If value is a callable object it must expect one or two arguments. Depending on the arity, the callable is invoked with the options hash as first argument with key as :root, and key singularized as second argument. Its return value becomes a new node.
- If value responds to to_xml the method is invoked with key as :root.
- Otherwise, a node with key as tag is created with a string
representation of value as text node. If value is
nil an attribute "nil" set to "true" is added.
Unless the option :skip_types exists and is true, an attribute
"type" is added as well according to the following mapping:
XML_TYPE_NAMES = { "Symbol" => "symbol", "Fixnum" => "integer", "Bignum" => "integer", "BigDecimal" => "decimal", "Float" => "float", "TrueClass" => "boolean", "FalseClass" => "boolean", "Date" => "date", "DateTime" => "datetime", "Time" => "datetime" }
By default the root node is "hash", but that’s configurable via the :root option.
The default XML builder is a fresh instance of Builder::XmlMarkup. You can configure your own builder with the :builder option. The method also accepts options like :dasherize and friends, they are forwarded to the builder.
more options
useful options are:
:root => ‘object’, :skip_instruct => true, :indent => 2
:builder can also be used to pass your own Builder::XmlMarkup instance.