REXML and new file problem? bug?

B

Bart Masschelein

Hello,

I want to use the REXML class, but encounter the following problem, if I
want to use an un-existant file:

file = File.new( "mydoc2.xml", "w+" ) # and this document does not exist
xml = Document.new(file)

I get the following error:

C:/ruby/lib/ruby/1.8/rexml/source.rb:128:in `initialize': undefined
method `[]' for nil:NilClass (NoMethodError)
from C:/ruby/lib/ruby/1.8/rexml/parsers/baseparser.rb:126:in `new'
from C:/ruby/lib/ruby/1.8/rexml/parsers/baseparser.rb:126:in `stream='
from C:/ruby/lib/ruby/1.8/rexml/parsers/baseparser.rb:100:in
`initialize'
from C:/ruby/lib/ruby/1.8/rexml/parsers/treeparser.rb:8:in `new'
from C:/ruby/lib/ruby/1.8/rexml/parsers/treeparser.rb:8:in `initialize'
from C:/ruby/lib/ruby/1.8/rexml/document.rb:177:in `new'
from C:/ruby/lib/ruby/1.8/rexml/document.rb:177:in `build'
from C:/ruby/lib/ruby/1.8/rexml/document.rb:45:in `initialize'
from C:/Documents and Settings/Bart/My
Documents/Programming/Ruby/Examples/XML/XMLTest1.rb:12:in `new'
from C:/Documents and Settings/Bart/My
Documents/Programming/Ruby/Examples/XML/XMLTest1.rb:12

So I put on my 'gutty' shoes, and have a look, and saw that in the file
C:/ruby/lib/ruby/1.8/rexml/source.rb, around 128, there is:
str = @source.read( 2 )
puts str, @source
if (str[0] == 254 && str[1] == 255) || (str[0] == 255 && str[1] ==
254)

However, as @source is an empty file (I know this because of the puts),
I get a nill as str, and hence, that error.

There are work-arounds for this (write to String and then to file), or
maybe Im not supposed to do this, but it looked un-Ruby, at first. If
the file is new, it should not try to parse it.

Just to let you know,

Bart.
 
Z

Zach Dennis

This is not a bug, from the documentation on the constructor:

"Constructor @param source if supplied, must be a Document, String, or
IO. Documents have their context and Element attributes cloned. Strings
are expected to be valid XML documents. IOs are expected to be sources
of valid XML documents"
^^^^^^^^^^^^^^^^^^^^^^

If you want to create a new xml document from scratch then please use
the syntax:
doc = REXML::Document.new

If you want to write it to something use an IO object...
doc.write obj_to_output_to

where obj_to_output_to can be any object that responds to <<, so an IO
object, a string, a StringIO, etc...

Zach
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,522
Members
44,995
Latest member
PinupduzSap

Latest Threads

Top