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