I am trying to change the data in the below XML file. I am sure about one thing that the data will be in <string>
tag but inside that it can be nested to any extent. So to do that I have come up with a recursive solution which seems like the right code but is not doing any change.
Recursion in C or C++ is easy as in that change is easily reflected in the actual parameter but in Ruby I am not able to figure out how to reflect that.
Source XML:
<document>
<string id="title">Continue without CableCARD?</string>
<string id="bodytext"/>
<string id = "f" >This is data1
<p>
<t>
this is data2
</t>
</p>
this is data3
</string>
</document>
Ruby code:
require 'nokogiri'
doc = Nokogiri::XML(File.open("d.xml"))
def rec_func(s)
if s.child.class == NilClass
return s
end
array = s.children()
array.each do |element|
if element == Nokogiri::XML::Text
s.content = s.content + "A"
else
element = rec_func(element)
puts "##########"
puts element
end
end
s.children = array # I added this statement as I was in doubt whether the changes in this array will be reflected in the parent s or not.
return s
end
doc.xpath("//string").each do |node|
k = rec_func node
puts "$$$$$$$$$$$$$$"
end
Please someone suggest any change in the code to make it work.