rubyxmllibxml-ruby

Declaring namespaces using libxml-ruby


I am using libxml-ruby for parsing XML.

I can able to create the xml file using libxml-ruby, but the problem is I am not able to declare the namespace for generated XML document.

Please help me how to create the namespace for newly generating XML.

The code written for creating xml is:

require 'rubygems' 
require 'libxml'

filename = 'something.xml'
stats_doc = LibXML::XML::Document.new()
stats_doc.root = LibXML::XML::Node.new('root_node') 
stats_doc.root << LibXML::XML::Node.new('elem1') 
stats_doc.save(filename, :indent => true, :encoding => LibXML::XML::Encoding::UTF_8)

Solution

  • You just have to create a new instance of the XML::Namespace class as described here. Below you can find modified version of your example.

    require 'rubygems' 
    require 'libxml'
    
    filename = 'something.xml'
    stats_doc = LibXML::XML::Document.new()
    stats_doc.root = LibXML::XML::Node.new('root_node')
    
    LibXML::XML::Namespace.new(stats_doc.root, 'soap', 'http://schemas.xmlsoap.org/soap/envelope/')
    
    stats_doc.root << LibXML::XML::Node.new('elem1')
    stats_doc.save(filename, :indent => true, :encoding => LibXML::XML::Encoding::UTF_8)