Libxml: trying to set encoding for a document

Hi all!

I have problems with setting encoding for an xml file. I want to produce
an
xml file which starts with

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

I tried the following code, but it gives initialized constant error when
I
try to set up document.encoding.

require ‘xml’

d = XML::Document.new()
#d.encoding = XML::Encoding::UTF_8
#=> uninitialized constant LibXML::XML::Encoding (NameError)
d.root = XML::Node.new(‘node’)
d.root << “Some info”
d.save(‘test.xml’, true)

produces:

<?xml version="1.0"?>

Some info

I tried to set encoding when saving the document, as shown in
documentation,
but without luck.

#d.save(‘test.xml’, :indent => true, :encoding => ‘UTF-8’)
#=>The second parameter (format) must be true or false (ArgumentError)
#d.save(‘test.xml’, :indent => true, :encoding => XML::Encoding::UTF_8)
#=> The second parameter (format) must be true or false (ArgumentError)

I checked ruby-libxml bug tracker and such bug has not been reported. So
I
am wondering if I am doing something wrong, or its a bug.

Thanks,

Diana

Diana J. [email protected] wrote:

I have problems with setting encoding for an xml file. I want to produce an
xml file which starts with

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

require ‘rubygems’
require ‘libxml’
doc = LibXML::XML::Document.new
puts doc.to_s #=> <?xml version="1.0" encoding="UTF-8"?>

m.

require ‘libxml’
doc = LibXML::XML::Document.new
puts doc.to_s #=> <?xml version="1.0" encoding="UTF-8"?>

You may also specify indentation and the explicit encoding
with parameters to the to_s method, like this:

doc.to_s(:indent => true, :encoding => XML::Encoding::UTF_8)

The documentation for XML::Document#to_s is quite buggy and
I’ve filed a ticket.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs