Python Text to XML Converter

This Python 2.7 program will convert each line from a text file copied to an Android XML resource string. It takes three inputs:

  • a keyword
  • input file name
  • resource type (in this case, it should always be string)

The key index to the string in the XML will be a combination of .

The program will filter out all lines containing reference to .jpg file. It will also escape single quote, double quote, and dash, as they are not acceptable Android resource characters. All blank lines are also filtered.

Problem with the program:
– right now it only reads ASCII. I’m in the process of making it Unicode compatible.

from sys import argv
import re
import codecs


print "Please enter story keyword: "
keyword = raw_input (prompt)

print "Please enter input file name:"
in_file = raw_input (prompt)

print"Please enter output file name:"
out_file = raw_input(prompt)

print "Please enter resource type (color, string, or dimen):"
r_type = raw_input(prompt)

print "Converting %r to %r" %(in_file, out_file)

#txt_in =, encoding='utf-8', mode='r')
#txt_out =, encoding='utf-8', mode='w+')
txt_in=open(in_file, 'r')
txt_out=open(out_file, 'w')



for line in txt_in:
    line=re.sub(r'\n', r'', line)
    line=re.sub(r"'", r"\'", line)
    line=re.sub(r'"', r'\"', line)
    line=re.sub(r'-', r'\-', line)
    if ((".jpg" in line) or (len(line)==0)):
        out_line = '\t<'+r_type+' name="'+keyword+str(linenum)+'">'+line+'\n'              
print "Done!"