class Nokogiri::XML::Document
def create_element(name, *contents_or_attrs, &block)
doc.create_element("div") { |node| node["class"] = "blue" if before_noon? }
*Example:* Passing a block to mutate the element
# =>
contents
doc.create_element("div", "contents", {"class" => "container"})
*Example:* An element with contents and attributes
# =>
doc.create_element("div", {"class" => "container"})
*Example:* An element with attributes
# =>
contents
doc.create_element("div", "contents")
*Example:* An element with contents
# =>
doc.create_element("div")
*Example:* An empty element without attributes
[Returns] Nokogiri::XML::Element
[Yields] `node` (Nokogiri::XML::Element)
- `contents_or_attrs` (\#to_s, Hash)
- `name` (String)
[Parameters]
A block may be passed to mutate the node.
- a non-Hash object that responds to \#to_s will be used to set the new node's contents
- a Hash argument will be used to set attributes
Arguments may be passed to initialize the element:
place it in the document tree.
Node#add_next_sibling, Node#replace, etc. which will both create an element (or subtree) and
document tree. Prefer one of the Nokogiri::XML::Node methods like Node#add_child,
This method is _not_ the most user-friendly option if your intention is to add a node to the
attributes.
Create a new Element with `name` belonging to this document, optionally setting contents or
create_element(name, *contents_or_attrs, &block) → Nokogiri::XML::Element
:call-seq:
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