Wednesday, 19 February 2014

Ruby: How to Read value from strings.xml files

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

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 =
    doc.elements.each("resources/string") do |ele|
    return all_strings_hash

Common Errors : uninitialized constant ReusableMethods::REXML (NameError)
/Users/tejasvi.manmatha/projects/ `read_xml'
/Users/tejasvi.manmatha/projects/ `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.