-
Notifications
You must be signed in to change notification settings - Fork 7
/
xmlparse.py
200 lines (166 loc) · 5.77 KB
/
xmlparse.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
from __future__ import print_function
from builtins import str
import xml.parsers.expat
import sys
from optparse import OptionParser
import re
elements = []
show_end = True
lasttextdata = ""
lstelements = []
def reset():
global elements, show_end, lstelements, lasttextdata
elements = []
show_end = True
lasttextdata = ""
lstelements = []
# 3 handler functions
def start_element(name, attrs):
global elements, show_end, lstelements, lasttextdata
lstattrs=list(sorted([ "%s=%s" % (k,v) for k,v in attrs.items() ]))
completename=name
if len(lstattrs):
completename+="&"+"&".join(lstattrs)
show_end = False
elements.append(completename)
#print 'Start element:', name, attrs
lstelements.append("/".join(elements))
#print "/".join(elements)
lasttextdata = ""
def end_element(name):
global elements, show_end, lstelements, lasttextdata
lasttextdata = ""
if show_end:
#print "/".join(elements) + "/"
lstelements.append("/".join(elements) + ";")
show_end = True
elements.pop()
#print 'End element:', name
def char_data(data):
global elements, show_end, lstelements, lasttextdata
#data = data.strip()
lasttextdata+=data
if lasttextdata.strip():
#show_end = True
lstelements.pop()
lstelements.append("/".join(elements)+"(%s)" % repr(lasttextdata.strip()))
#print "/".join(elements)+ "(%s)" % repr(data)
def unmap(lines):
runmap = re.compile(r"^(?P<depth>/*)(?P<tagname>\w+)(?P<attrs>&[^\(]+)*(?P<txt>\(.+\))?$")
# depthlevel
# tagname
elementpool = []
text = []
for line in lines:
line = line.strip()
if line[-1] == ";": continue
rg1 = runmap.match(line)
if not rg1:
print("error:")
print(line)
break
depth = len(rg1.group('depth'))
tagname = str(rg1.group('tagname'))
t_attrs = rg1.group('attrs')
attrs = []
if t_attrs:
lattrs = t_attrs[1:].split("&")
for attr in lattrs:
key, val = attr.split("=")
attrs.append( (key,val) )
t_txt = rg1.group('txt')
txt = ""
if t_txt:
txt = eval(t_txt[1:-1])
while depth < len(elementpool):
toclose = elementpool.pop()
text.append("</%s>" % toclose)
text.append("\n" + " " * len(elementpool))
if depth == len(elementpool):
#print depth, tagname, attrs, txt
txtattrs = ""
if attrs:
for k,v in attrs:
txtattrs+=" %s=\"%s\"" % (k,v)
if txt:
txt = txt.encode("utf-8")
txt = txt.replace("&","&")
txt = txt.replace("<","<")
else:
txt = ""
text.append("<%s%s>%s" % (tagname, txtattrs,txt))
elementpool.append(tagname)
else:
print("error:")
print(depth, len(elementpool))
break
while len(elementpool):
toclose = elementpool.pop()
text.append("</%s>" % toclose)
text.append("\n" + " " * len(elementpool))
return text
def main():
parser = OptionParser()
#parser.add_option("-f", "--file", dest="filename",
# help="write report to FILE", metavar="FILE")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose", default=True,
help="don't print status messages to stdout")
parser.add_option("--optdebug",
action="store_true", dest="optdebug", default=False,
help="debug optparse module")
parser.add_option("--debug",
action="store_true", dest="debug", default=False,
help="prints lots of useless messages")
(options, args) = parser.parse_args()
if options.optdebug:
print(options, args)
if len(args) < 2:
print("Se necesita al menos una accion y un argumento extra.")
print("xmlparse (map|unmap) file1 [file2] [file3]")
return
action = args.pop(0)
if action == "map":
global lstelements
separators = [
"hbox",
"vbox",
"grid",
]
r1 = re.compile("/widget")
for fname in args:
p = xml.parsers.expat.ParserCreate()
p.StartElementHandler = start_element
p.EndElementHandler = end_element
p.CharacterDataHandler = char_data
fhandler = open(fname)
fw = open(fname+".map","w")
reset()
p.ParseFile(fhandler)
for t in lstelements:
elems = t.split("/")
lbox = []
for n,e in enumerate(elems):
if e in separators: lbox.append(n)
if len(lbox)>1:
nlbox = lbox[-2]
while len(elems[nlbox:]) < 2:
nlbox -= 1
else:
nlbox = 0
fw.write("/"*(len(elems)-1) + "/".join(elems[-1:])+ "\n")
#print "/"*(len(elems)-1) + "/".join(elems[-1:])
lstelements = []
fhandler.close()
fw.close()
elif action == "unmap":
for fname in args:
fhandler = open(fname)
fw = open(fname+".ui","w")
for line in unmap(fhandler):
fw.write(line)
fw.close()
fhandler.close()
else:
print("Unkown action '%s'" % action)
if __name__ == "__main__": main()