簡體   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