Skip to content

Instantly share code, notes, and snippets.

@pardom-zz
Last active December 13, 2015 21:39
Show Gist options
  • Save pardom-zz/4979099 to your computer and use it in GitHub Desktop.
Save pardom-zz/4979099 to your computer and use it in GitHub Desktop.
Python script to look for xml literal strings in Android resources, and convert them to string resources.
#!/usr/bin/env python
# encoding: utf-8
import os
import sys
import xml.etree.ElementTree as ET
import re
idAttrib = '{http://schemas.android.com/apk/res/android}id'
def main(argv):
output = open('strings.xml', 'w')
resources = []
for arg in argv:
parse_path(arg, resources)
for res in resources:
output.write("%s\n" % res)
output.close()
def parse_path(path, resources):
if os.path.isdir(path):
for root, dirs, files in os.walk(path):
for file in files:
parse_path(os.path.join(root, file), resources)
else:
parse_file(path, resources)
def parse_file(file, resources):
if not file.endswith('.xml'):
return
tree = ET.parse(file)
root = tree.getroot()
fileName = file[file.rfind('/')+1:]
fileComment = '\n<!-- ' + fileName + ' -->'
parse_node(root, resources, fileComment)
def parse_node(root, resources, fileComment):
for child in root:
parse_node(child, resources, fileComment)
for key, value in child.attrib.iteritems():
if not key.endswith('text'):
continue
if value.startswith('@'):
continue
if idAttrib in child.attrib:
id = child.attrib[idAttrib]
id = id[id.find('/')+1:]
else:
id = value.lower().replace(' ', '_')
id = re.sub('[^a-z_]+', '', id)
id = "_".join(id.split('_')[:3])
res = '<string name="' + id + '">'+ value + '</string>'
if res in resources:
res = '<!-- @string/' + id + ' -->'
if fileComment not in resources:
resources.append(fileComment)
resources.append(res)
if __name__ == '__main__':
main(sys.argv[1:])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment