I am having trouble editing an XML file correctly. I want to remove certain elements and then add new ones.
<project>
<option>
<name>foo</name>
<state>0</state>
</option>
<option>
<name>bar</name>
<state>foo/apple</state>
<state>foo/orange</state>
</option>
</project>
I want to remove the state
s apple and orange and insert grape, lemon and lime. I have tried with this code:
#!/usr/bin/ruby -w
require 'fileutils'
require 'rexml/document'
require 'find'
include REXML
path = 'C:\Users\GustavWi\Documents\Gustav\help.xml'
xmlfile = File.new(path)
xmldoc = Document.new(xmlfile)
str_new_elements =["grape","lemon","lime"]
xmldoc.elements.each("project/option") do |parent|
if parent.elements['name'].text == 'bar'
parent.elements.each do |element|
str = element.text.split('/')
if str[0] == 'foo'
parent.delete_element(element)
end
end
str_new_elements.each do |dir|
state = Element.new("state")
state.text = dir
parent.add_element(state)
end
end
end
File.open(path,"w") do |data|
xmldoc.write(data)
end
The problem is that the output is:
<project>
<option>
<name>foo</name>
<state>0</state>
</option>
<option>
<name>bar</name>
<state>grape</state><state>lemon</state><state>lime</state></option>
</project>
The problem is the empty lines and the missing indentation of the new elements.
I am using Ruby 1.8.6 so that might be a problem but I have not seen any info that this is a problem in 1.8.6.
Almost the same problem can be seen in the book "Programming Ruby The Pragmatic Programmers' Guide" on page 726.