6

I have the following code:

builder = Nokogiri::XML::Builder.new(:encoding => 'UTF-8') do |xml|
  xml.myRoot do |xml|
    xml.oneChild
    xml.anotherChild
  end
end

Now I want to append a few child nodes to myRoot using the builder (in a second step, I know how to append them straight away). How can I do that?

I've tried this:

node = builder.doc.xpath('//myRoot/oneChild').first
Nokogiri::XML::Builder.with(node) do |xml|
  xml.childOfOneChild 'Im a child of oneChild'
end

Which doesn't work. They won't stick to the element, it's just an empty oneChild.

1 Answer 1

16

Your code produces the following XML, which seems to meet your specifications. It doesn't produce an empty oneChild, at any rate. If this isn't what you're looking for, can you tell us what your ideal output would be?:

builder = Nokogiri::XML::Builder.new(:encoding => 'UTF-8') do |xml|
  xml.myRoot do |xml|
    xml.oneChild
    xml.anotherChild
  end
end

puts builder.to_xml

# <?xml version="1.0" encoding="UTF-8"?>
# <myRoot>
#   <oneChild/>
#   <anotherChild/>
# </myRoot>   

node = builder.doc.xpath('//myRoot/oneChild').first
Nokogiri::XML::Builder.with(node) do |xml|
  xml.childOfOneChild 'Im a child of oneChild'
end

puts builder.to_xml

# <?xml version="1.0" encoding="UTF-8"?>
# <myRoot>
#   <oneChild>
#     <childOfOneChild>Im a child of oneChild</childOfOneChild>
#   </oneChild>
#   <anotherChild/>
# </myRoot>
Sign up to request clarification or add additional context in comments.

1 Comment

I wonder, where the is the OP? this worked for me, thanks very much. documentation: rdoc.info/github/tenderlove/nokogiri/master/Nokogiri/XML/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.