How do I create a child element within a Nokogiri node?

5.6k views Asked by At

I’m using Rails 4.2.7 with Nokogiri. I’m having trouble creating a child node. I have the following code

general = doc.xpath("//lomimscc:general")
description = Nokogiri::XML::Node.new "lomimscc:description", doc
string = Nokogiri::XML::Node.new "lomimscc:string", doc
string.content = scenario.abstract
string['language'] = 'en'
description << string
general << description

I want the “description” element to be a child element of the “general” element (and similarly I want the “string” element to be a child of the “description” element). However what is happening is that the description element is appearing as a sibling of the general element. How do I make the element appear as a child instead of a sibling?

2

There are 2 answers

3
the Tin Man On

The tutorials show how to do this in "Creating new nodes", but the simple example is:

require 'nokogiri'

doc = Nokogiri::XML('<root/>')
doc.at('root').add_child('<foo/>')
doc.to_xml # => "<?xml version=\"1.0\"?>\n<root>\n  <foo/>\n</root>\n"

Nokogiri makes it easy to build nodes using a string that contains the markup or nodes you want to add.

You should be able to build upon this easily.

This is also noted throughout the Node documentation any place you see "node_or_tags".

0
Dave On

When I changed

general = doc.xpath("//lomimscc:general")

to

general = doc.xpath("//lomimscc:general").first

then everything worked as far as creating child nodes.