Google+ Followers

Wednesday, 19 February 2014

Ruby: How to Read value from strings.xml files

Sample XML format
<?xml version="1.0" encoding="UTF-8"?>
<resources>
  <string name="september">September</string>
  <string name="shortdate">DD.MM.YYYY</string>
</resources>

Ruby code to read the XML

resources/string in below must be used to represent the parent child heirarchy


#require the gem and module required
require 'rexml/document'  
#Read language strings by default or else read specified file
# filename can be absolute path or relative path
all_strings_hash will be return value which contains strings and values 
def read_xml(filename="xxx/filename.xml")
    doc = REXML::Document.new(File.new(filename))
    all_strings_hash={}
    doc.elements.each("resources/string") do |ele|
      all_strings_hash[ele.attributes["name"]]=ele.text
    end
    return all_strings_hash
end


Common Errors : uninitialized constant ReusableMethods::REXML (NameError)
/Users/tejasvi.manmatha/projects/meine.tui.ui-automation/features/common/support/reusable_methods.rb:106:in `read_xml'
/Users/tejasvi.manmatha/projects/meine.tui.ui-automation/features/common/support/reusable_methods.rb:36:in `get_localized_string'

Solution: put this line at beginning of ruby file require 'rexml/document' 

1 comment:

  1. Hello! If you need to translate strings.xml files, I suggest using a collaborative translation management platform like POEditor that can help with the workflow automation and simplify it.

    ReplyDelete