简体   繁体   中英

Ruby: Can't save document with Libxml-ruby

From the libxml-ruby API docs ( http://libxml.rubyforge.org/rdoc/index.html ), under LibXML::XML::Document, I tried the following:

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

... which resulted in this error:

parse_stats.rb:26:in `save': can't convert String into Integer (TypeError)

(where the last line in the block above was line 26).

I tried changing the file name to an integer, which gave me this:

parse_stats.rb:26:in `save': wrong argument type Fixnum (expected String) (TypeError)

So I gathered that I need to use a string, but strings don't seem to work. Since I seem to be unable to find any examples of libxml-ruby in action off Google, I'm at a loss. Any help would be very appreciated, or links to any online example where I can see how libxml-ruby is used for creating XML documents.

libxml-ruby 1.1.3 rubygems 1.3.1 ruby 1.8.7

Seems that the problem is with encoding. Try XML::Encoding::UTF_8 instead of "utf-8".

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM