使用Ruby脚本更新Android Strings.xml

时间:2013-05-10 19:06:02

标签: android ruby xml

我想使用基于Ruby的脚本来浏览Android中的strings.xml文件以更新某些值。 例如: 这是原始的xml文件

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

我想在运行ruby脚本之后成为这个:

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

我对ruby完全不熟悉,但我能够让它读取xml文件......只是不确定如何更新值。

(如果您想知道,我正在这样做,所以我可以将我的应用程序贴上白色标签并将其出售给企业。这将有助于加快这一过程。)

3 个答案:

答案 0 :(得分:4)

我找到了办法。

  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

答案 1 :(得分:0)

警告,如果您使用来自android代码的strings.xml文件中的资源,使用R.string类,那么从外部修改XML将无效。

编译应用程序时会创建R.string类,因此如果在编译后修改XML文件,更改将不会在您的应用程序中生效。

答案 2 :(得分:0)

超级有帮助!为了后人的缘故......我选择了:

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

当您的字符串键(名称)是唯一的(Android Studio强制执行以便您可以信任它们时),这种方法很有效。您可以在中间抛出尽可能多的字符串编辑,然后保存更改,而不必担心弄乱任何其他值。