Rectangle 27 0

ruby Add prefix to XML root node?


attrs = {
  'xmlns' => '',
  'xmlns:req' => 'http://www.google.com',
  'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance',
  'schemaVersion' => '1.0',
}
builder = Nokogiri::XML::Builder.new do |xml|
  xml['req'].Request(attrs) {
    xml.LanguageCode('en')
    xml.Enabled('Y')
  }
end

builder.to_xml # =>
# <?xml version="1.0"?>
# <req:Request xmlns="" xmlns:req="http://www.google.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" schemaVersion="1.0">
#   <LanguageCode>en</LanguageCode>
#   <Enabled>Y</Enabled>
# </req:Request>

@matt: hmm, makes sense. I've updated the answer.

I think you need 'xmlns' => '' (i.e. an empty string rather than the string default). The spec says The attribute value in a default namespace declaration MAY be empty. This has the same effect, within the scope of the declaration, of there being no default namespace. Using default will put all unprefixed elements into the namespace named default, not no namespace.

Try adding the attribute xmlns="", which seems to hint to the XML builder that elements should be in the default namespace unless otherwse declared. I believe the resulting document is semantically equivalent to your example despite its presence...

Note