Kent Andersen Kent Andersen - 3 months ago 8
Ruby Question

Update Android Strings.xml with Ruby script

I'd like to use a Ruby based script to go through the strings.xml file in Android to update certain values.
For example:
This is the original xml file

<resources>
<string name="accounts">accounts</string>
</resources>


I want it to become this after running the ruby script:

<resources>
<string name="accounts">my accounts</string>
</resources>


I'm completely new to ruby, but I was able to get it to read a xml file....just not sure how to update the values.

(In case you are wondering, I'm doing this so I can white-label my app and sell it to businesses. This will help speed up the process a lot.)

Answer

I found a way to do it.

  require 'rubygems'
  require 'nokogiri'

  #opens the xml file
  io = File.open('/path/to/my/strings.xml', 'r')
  doc = Nokogiri::XML(io)
  io.close

  #this line looks for something like this: "<string name="nameOfStringAttribute">myString</string>"
  doc.search("//string[@name='nameOfStringAttribute']").each do |string|

  #this line updates the string value
  string.content = "new Text -- IT WORKED!!!!"

  #this section writes back to the original file
  output = File.open('/path/to/my/strings.xml', "w")
  output << doc
  output.close

  end