0

I am using Nokogiri to generate XML. I would like to add a namespace prefix to the XML root node only but the problem is applying the prefix to the first element it get apply to all children elements.

This is my expected result:

<?xml version="1.0" encoding="UTF-8"?>
<req:Request 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>
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Ravi
  • 163
  • 1
  • 5
  • 2
    Could you paste a snippet of your code generating the XML ? also you could check this doc : http://www.rubydoc.info/github/sparklemotion/nokogiri/master/Nokogiri/XML/Builder – flafoux May 18 '15 at 16:52
  • 1
    Welcome to Stack Overflow. You're asking us to debug code that we can't see. That won't work. You need to show us a minimal example of the code you've written, explain why you think it doesn't work, and then we can help you. Otherwise it sounds like you're asking us to write the code for you. – the Tin Man May 18 '15 at 18:01

1 Answers1

4

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...

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>
maerics
  • 151,642
  • 46
  • 269
  • 291
  • I think you need `'xmlns' => ''` (i.e. an empty string rather than the string `default`). The [spec says](http://www.w3.org/TR/REC-xml-names/#defaulting) “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. – matt May 18 '15 at 21:28