Pawang Uler

My experience with python programming language

2009/06/08

Replace duplicate widget name in the glade file

Even in the release notes in Glade Interface Designer stated that duplicate widget name is not allowable in a glade project.
The duplicate widget names are still occur in the glade file.
Some times at the run time gtk builder raise an error about duplicate widget name.

I create a tool to replace a duplicate widget name with appending a postfix after original widget name.


'''
Copyright 2009 Mige Harimurti


This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.


'''



import xml.parsers.expat
import sys


id_list = {}

xml_out = ''

# 3 handler functions

def start_element(name, attrs):
#print 'Start element:', name, attrs
global xml_out
if 'id' in attrs:
if attrs['id'] in id_list:
#print '\t %s duplicate.' % attrs['id']
id_list[attrs['id']] += 1
attrs['id'] = '%s%s' % (attrs['id'],id_list[attrs['id']])
else:
id_list[attrs['id']] = 1
attribute_list = ""
for k in attrs:
attribute_list = '%s %s="%s"' % (attribute_list,k,attrs[k])

xml_out = '%s<%s %s>' % (xml_out,name, attribute_list)

def end_element(name):
#print 'End element:', name
global xml_out
xml_out = '%s</%s>' % (xml_out,name)


def char_data(data):
global xml_out
xml_out = '%s%s' % (xml_out, data)


if __name__ == "__main__":
xml_file = sys.argv[1]
p = xml.parsers.expat.ParserCreate()

p.returns_unicode = False
p.StartElementHandler = start_element
p.EndElementHandler = end_element
p.CharacterDataHandler = char_data

xfo = open(xml_file)

xml_out = '<?xml version="1.0"?>\n'
p.ParseFile(xfo)
print xml_out

#~ for k in id_list:
#~ if id_list[k] > 1:
#~ print "%s:%s" % (k,id_list[k])