简体   繁体   English

使用Ruby脚本更新Android Strings.xml

[英]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. 我想使用基于Ruby的脚本来检查Android中的strings.xml文件以更新某些值。 For example: This is the original xml file 例如:这是原始的xml文件

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

I want it to become this after running the ruby script: 我希望它在运行ruby脚本后变为:

<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. 我对ruby完全陌生,但是我能够获取它来读取xml文件...。只是不确定如何更新值。

(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. 请注意,如果您使用的是Android代码中strings.xml文件中的资源,请使用R.string类,那么从外部修改XML将不起作用。

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. R.string类是在编译应用程序时创建的,因此,如果在编译后修改XML文件,更改将不会在您的应用程序中生效。

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). 当您的字符串键(名称)是唯一的(Android Studio强制执行,因此您可以相信它们会是唯一的)时,这种方法很好用。 You can throw as many string edits in the middle there and then save the changes without worrying about messing up any other values. 您可以在中间进行尽可能多的字符串编辑,然后保存更改,而不必担心弄乱其他任何值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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