Method: Nokogiri::XML::Document#create_element

Defined in:
lib/nokogiri/xml/document.rb

#create_element(name, *contents_or_attrs, &block) ⇒ Object

:call-seq:

create_element(name, *contents_or_attrs, &block) 

Create a new Element with ‘name` belonging to this document, optionally setting contents or attributes.

This method is not the most user-friendly option if your intention is to add a node to the document tree. Prefer one of the Nokogiri::XML::Node methods like Node#add_child, Node#add_next_sibling, Node#replace, etc. which will both create an element (or subtree) and place it in the document tree.

Arguments may be passed to initialize the element:

  • a Hash argument will be used to set attributes

  • a non-Hash object that responds to #to_s will be used to set the new node’s contents

A block may be passed to mutate the node.

Parameters
  • ‘name` (String)

  • ‘contents_or_attrs` (#to_s, Hash)

Yields

‘node` (Nokogiri::XML::Element)

Returns

Nokogiri::XML::Element

Example: An empty element without attributes

doc.create_element("div")
# => <div></div>

Example: An element with contents

doc.create_element("div", "contents")
# => <div>contents</div>

Example: An element with attributes

doc.create_element("div", {"class" => "container"})
# => <div class='container'></div>

Example: An element with contents and attributes

doc.create_element("div", "contents", {"class" => "container"})
# => <div class='container'>contents</div>

Example: Passing a block to mutate the element

doc.create_element("div") { |node| node["class"] = "blue" if before_noon? }


276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
# File 'lib/nokogiri/xml/document.rb', line 276

def create_element(name, *contents_or_attrs, &block)
  elm = Nokogiri::XML::Element.new(name, self, &block)
  contents_or_attrs.each do |arg|
    case arg
    when Hash
      arg.each do |k, v|
        key = k.to_s
        if key =~ NCNAME_RE
          ns_name = Regexp.last_match(1)
          elm.add_namespace_definition(ns_name, v)
        else
          elm[k.to_s] = v.to_s
        end
      end
    else
      elm.content = arg
    end
  end
  if (ns = elm.namespace_definitions.find { |n| n.prefix.nil? || (n.prefix == "") })
    elm.namespace = ns
  end
  elm
end