简体   繁体   中英

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.)

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

Be warned, if you are using the resources from the strings.xml file from the android code, using the R.string class, then modifying the XML externally will not work.

The R.string class is created when you compile your application, so if you modify the XML file after compilation, the changes will not take effect in your application.

Super helpful! For posterity's sake...I opted for:

doc = Nokogiri::XML(File.open('path_to/strings.xml')))

doc.search("//string[@name='my_string_attribute']").first.content = "my new string value"

File.open('path_to/strings.xml', 'w') { |f| f.print(doc.to_xml) }

That works well when your string key (name) is unique (which Android Studio enforces so you can trust that they will be). You can throw as many string edits in the middle there and then save the changes without worrying about messing up any other values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM