Defindit Docs and Howto Home

This page last modified: Sep 23 2010
keywords:nokogiri,builder,xml,example,code,working,child,parent,node,tree,root,doc,document
description:Working code examples for adding a child node to a Nokogiri Builder object.
title:Nokogiri Builder examples.

Table of contents
-----------------
Introduction
Download the code examples
Code fragments



Introduction
------------

Nokogiri Builder is a class to create XML documents. However, it is
lacking in documentation and examples so I worked out how to add a
child element to an existing Builder tree. I found two cases where I
needed to do this:

1) Looping and conditionals where the code involved either would not
work in a Builder constructor, or where the code had to add elements
that could not be known at the time Builder was first invoked

2) I wanted to add an external XML document to my Builder document.




Download the code examples
--------------------------

http://defindit.com/readme_files/nokogiri_examples.tar




Code fragments
--------------

This is not executable code. It is here for a quick overview. Download
the tar file with the examples for executable code. The tar file
includes several examples and a transcript recorded when I ran the
examples so you'll see the expected output.


# Code fragment 1: Use builder to create our main document. This gets
# us ready for the next code fragments.

@builder = Nokogiri::XML::Builder.new {
  wrap_it( 'WRAP' => "demo") {
    # The parent element is "wrap_it", thus method parent()
    # returns a Nokogiri::XML::Element that we can operate on later.
    @fs_parent = parent;
  }
}

# Code fragment 2: Given that we have somehow (with an accessor) put
# the value of @fs_parent into fs_parent, this is the simple case of
# adding a literal child element

fs_parent.add_child("<test_ele>literal string element add</test_ele>")


# Code fragment 2.1: The more complex case of adding an entire document as the child
# element (child tree in this case). Again, assume that we used an
# accessor to put the value of @fs_parent into the local variable
# fs_parent

fbuilder = Nokogiri::XML::Builder.new {
  new_element(:ID => "stuff", :USE => "directory") {
    inner_element(arg)
  }
}

fs_parent.add_child(fbuilder.doc.root)



# Code fragment 3: Here we parse an external XML document, and add it
# as the child. We're doing this directly in the Builder call, so
# there's no saving of the parent node as in the examples above.

@builder = Nokogiri::XML::Builder.new {
  mdWrap( 'MDTYPE' => "FITS") {
    xmlData {
      fits_xml = Nokogiri::XML(IO.read("noko_test.xml"))
      parent.add_child(fits_xml.root)
    }
  }
}