繁体   English   中英

使用Ruby脚本更新Android Strings.xml

[英]Update Android Strings.xml with Ruby script

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

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

我希望它在运行ruby脚本后变为:

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

我对ruby完全陌生,但是我能够获取它来读取xml文件...。只是不确定如何更新值。

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

我找到了一种方法。

  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

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

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

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

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强制执行,因此您可以相信它们会是唯一的)时,这种方法很好用。 您可以在中间进行尽可能多的字符串编辑,然后保存更改,而不必担心弄乱其他任何值。

暂无
暂无

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

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