I’m trying to edit an XML file and replace strings with ruby variables.
For now this is my code :
<?xml version="1.0" encoding="US-ASCII"?>
<Standart-Profile>
<class1>
<class2>
<class3>
<value1>old_A</value2>
<value1>old_B</value2>
<value1>old_C</value2>
</class3>
</class2>
</class1>
</Standart-Profile>
And this is the Ruby file :
require "rexml/text"
require 'rexml/document'
include REXML
def generate_2
...
end
def generate_1
...
end
File.open('Standart-Profile.xml') do |config_file|
config = Document.new(config_file)
config.root.elements['old_A'].text = 'generate_1'
config.root.elements['old_B'].text = 'generate_2'
config.root.elements['old_C'].text = 'generate_1'
formatter = REXML::Formatters::Default.new
File.open('New-Profile.xml', 'w') do |result|
formatter.write(config, result)
end
end
But I keep getting this error :
Final-Tool-Kit.rb:19:in `block in <main>': undefined method `text=' for nil:NilC
lass (NoMethodError)
from test.rb:16:in `open'
from test.rb:16:in `<main>'
Your problem is that you’re looking for an element with the name
old_Awhen you should be looking for an element with the text contents ofold_A.Here’s a solution using Nokogiri, which I find more convenient than REXML:
If you actually want to call a
generate_1method (as you have defined) then you would instead use:Edit: Here’s one way to do it with XPath in REXML (after I fixed the source XML to be valid):