2013-05-10 46 views
2

我想使用基於Ruby的腳本瀏覽Android中的strings.xml文件以更新某些值。 例如: 這是原始的XML文件使用Ruby腳本更新Android Strings.xml

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

我希望它運行Ruby腳本之後成爲了這個:

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

我完全新的紅寶石,但我能讓它讀取一個xml文件....只是不知道如何更新值。

(如果你想知道,我這樣做讓我可以白色標籤我的應用程序,並把它賣給企業,這將有助於加快這一進程了不少。)

回答

3

我找到了一種方法來做到這一點。

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 
0

被警告,如果你正在使用來自android代碼的strings.xml文件中的資源,使用R.string類,然後從外部修改XML將不起作用。

R.string類是在編譯應用程序時創建的,所以如果在編譯後修改XML文件,這些更改將不會在您的應用程序中生效。

+0

我不打算從代碼更改Strings.xml文件。這是需要連接到生成APK之前更改值的構建服務器的問題 – 2013-05-10 19:10:32

+0

好吧,那麼不要那麼着急。雖然不能幫助你,但我會建議使用正則表達式來改變它。如果是linux,你可以使用sed&awk。 – tbkn23 2013-05-10 19:16:43

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中強制執行,所以你可以相信他們會)。您可以在中間放置儘可能多的字符串編輯,然後保存更改,而不必擔心會混淆其他任何值。