24

Possible Duplicate:
Print an XML document without the XML header line at the top

I have a problem with Nokogiri::XML::Builder. I am generating XML wth this code:

builder = Nokogiri::XML::Builder.new do 
    request {
        data '1'
    }
end

And the result is:

<?xml version="1.0" encoding="UTF-8"?><request><data>1</data></request>

How can I remove:

<?xml version="1.0" encoding="UTF-8"?>

from my XML?

0

2 Answers 2

32

Maybe take just the root node of the current Document object being built – .doc – instead of the whole document?

builder.doc.root.to_s
2
  • it raise error(Document already has a root node). But builder.parent.root.to_s doesn't. Thank. You make me thing in right way )
    – mibon
    Jan 17, 2012 at 13:47
  • 7
    Should be builder.doc.root.to_xml (or to_s).
    – Phrogz
    Jan 18, 2012 at 1:44
7

A quick and dirty answer is to tell Nokogiri to reparse the resulting output, then look at the root:

require 'nokogiri'

builder = Nokogiri::XML::Builder.new do 
  request {
    data '1'
  }
end

puts Nokogiri::XML(builder.to_xml).root.to_xml

Which outputs:

<request>
  <data>1</data>
</request>

Not the answer you're looking for? Browse other questions tagged or ask your own question.