R
Rob Boellaard
Hello,
I am trying to get some simple create/update/delete xml-element to
work with REXML, but I run into trouble when writing to file. Here's a
code example:
def save
file = File.open(@@filePath, "r+")
doc = Document.new(file)
root = doc.root
#create/update/delete elements in the root
file.rewind
formatter = REXML::Formatters:efault.new( 5 )
formatter.write( doc, file)
file.close
end
at first I was just adding and updating, and I noticed I needed to put
the line:
file.rewind
or it would just append the root elements to the existing ones in the
file, thereby creating doubles.
Now that I have reached delete, I get the following behaviour:
say the file contains:
element_1
element_2
element_3
element_4
and I want to delete element_2, the result in the file is:
element_1
element_3
element_4
element_4
to me, this:
formatter.write( doc, file)
implies that the entire xml doc would be written to the file, and as a
result the file should only contain the doc (or the root of the doc),
and nothing else.
I am not very experienced in Ruby, and tried to resolve this way:
def save
file = File.open(@@filePath, "r+")
doc = Document.new(file)
root = doc.root
file.close
#create/update/delete elements in the root
file = File.open(@@filePath, "w")
formatter = REXML::Formatters:efault.new( 5 )
formatter.write( doc, file)
file.close
end
this works, but I feel there should be a better approach, because
having to open the same file twice seems awkward .
Thanks in advance,
Rob
I am trying to get some simple create/update/delete xml-element to
work with REXML, but I run into trouble when writing to file. Here's a
code example:
def save
file = File.open(@@filePath, "r+")
doc = Document.new(file)
root = doc.root
#create/update/delete elements in the root
file.rewind
formatter = REXML::Formatters:efault.new( 5 )
formatter.write( doc, file)
file.close
end
at first I was just adding and updating, and I noticed I needed to put
the line:
file.rewind
or it would just append the root elements to the existing ones in the
file, thereby creating doubles.
Now that I have reached delete, I get the following behaviour:
say the file contains:
element_1
element_2
element_3
element_4
and I want to delete element_2, the result in the file is:
element_1
element_3
element_4
element_4
to me, this:
formatter.write( doc, file)
implies that the entire xml doc would be written to the file, and as a
result the file should only contain the doc (or the root of the doc),
and nothing else.
I am not very experienced in Ruby, and tried to resolve this way:
def save
file = File.open(@@filePath, "r+")
doc = Document.new(file)
root = doc.root
file.close
#create/update/delete elements in the root
file = File.open(@@filePath, "w")
formatter = REXML::Formatters:efault.new( 5 )
formatter.write( doc, file)
file.close
end
this works, but I feel there should be a better approach, because
having to open the same file twice seems awkward .
Thanks in advance,
Rob