File: dtd2schema.py

package info (click to toggle)
qm 1.1.3-1
  • links: PTS
  • area: main
  • in suites: woody
  • size: 8,628 kB
  • ctags: 10,249
  • sloc: python: 41,482; ansic: 20,611; xml: 12,837; sh: 485; makefile: 226
file content (331 lines) | stat: -rw-r--r-- 9,596 bytes parent folder | download | duplicates (2)
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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
#!/usr/bin/python

"""
This script converts DTDs to XML Schemas, according to the 20000407 WD.
It can do simple reverse-engineering of attribute groups.
"""

# Todo
# - make better names for attrgroups?
# - make a SchemaWriter class (to hold common references)
# - start doing reverse engineering to create modelGroups?

from xml.parsers.xmlproc import xmldtd
import sys, types, os.path, string

usage = \
"""
Usage:

  python dtd2schema.py <inputfile> [<outputfile>]

  Input file names can be URLs.
  
  If the output file name is omitted, it will be inferred from the
  input file name. Note that this inference does not work for URLs.
"""

version = "0.2"

# ===== UTILITY FUNCTIONS

class CountingDict:

    def __init__(self):
        self._items = {}

    def count(self, item):
        try:
            self._items[item] = self._items[item] + 1
        except KeyError:
            self._items[item] = 1

    def clear(self):
        self._items = {}

    def keys(self):
        return self._items.keys()
        
    def __getitem__(self, item):
        return self._items[item]

    def __delitem__(self, item):
        del self._items[item]

class AttributeInfo:
    """This class holds information about reverse-engineered attribute
    groupings."""

    def __init__(self):
        self._shared_attrs = {}
        self._shared_attrs_on_elem = {}
        self._count = CountingDict()
        self._groupnames = {}

    def count(self, attrname):
        self._count.count(attrname)

    def new_attr(self, elemname, attr):
        attrname = attr.get_name()
        self._count.count(attrname)
        
        if self._shared_attrs.has_key(attrname):
            shared = self._shared_attrs[attrname]
            if shared != None and not compare_attrs(shared, attr):
                self._shared_attrs[attrname] = None

        else:
            self._shared_attrs[attrname] = attr
        
    def remove_single_attributes(self):
        "Removes attributes that only occurred once."
        for attrname in self._shared_attrs.keys():
            if self._shared_attrs.get(attrname) != None:
                if self._count[attrname] < 2:
                    self._shared_attrs[attrname] = None
        
        self._count.clear()

    def find_groups(self, elem):
        shared = tuple(filter(self._shared_attrs.get, elem.get_attr_list()))
        self._shared_attrs_on_elem[elem.get_name()] = shared
        if shared:
            self._count.count(shared)

    def remove_single_groups(self):
        "Removes groups that only occurred once."
        for group in self._count.keys():
            if self._count[group] < 2:
                del self._count[group]

    def get_groups(self):
        return self._count.keys()

    def get_attribute(self, name):
        return self._shared_attrs[name]

    def get_shared_attrs_on_elem(self, elemname):
        return self._shared_attrs_on_elem[elemname]

    def make_name(self, group):
        name = "group" + str(len(self._groupnames) + 1)
        self._groupnames[group] = name
        return name

    def get_group_name(self, group):
        return self._groupnames[group]
    
def escape_attr_value(value):
    value = string.replace(value, '&', '&amp;')
    value = string.replace(value, '"', '&quot;')
    return string.replace(value, '<', '&lt;')

# ===== REVERSE ENGINEERING

def compare_attrs(attr1, attr2):
    return attr1.get_name() == attr2.get_name() and \
           attr1.get_type() == attr2.get_type() and \
           attr1.get_decl() == attr2.get_decl() and \
           attr1.get_default() == attr2.get_default()

def find_attr_groups(dtd):
    # first pass: find attributes that occur more than once
    attrinfo = AttributeInfo()
    for elemname in dtd.get_elements():
        elem = dtd.get_elem(elemname)
        
        for attrname in elem.get_attr_list():
            attrinfo.new_attr(elemname, elem.get_attr(attrname))

    attrinfo.remove_single_attributes()

    # second pass: group the recurring attributes
    for elemname in dtd.get_elements():
        elem = dtd.get_elem(elemname)
        attrinfo.find_groups(elem)

    attrinfo.remove_single_groups()
    return attrinfo
        
# ===== COMPONENT FUNCTIONS

def write_attribute_group(out, group, attrinfo):
    groupname = attrinfo.make_name(group)
    out.write('  <attributeGroup name="%s">\n' % groupname)
    for attrname in group:
        write_attr(out, attrinfo.get_attribute(attrname))
    out.write('  </attributeGroup>\n')

declmap = {"#REQUIRED" : "required",
           "#IMPLIED"  : "optional",
           "#DEFAULT"  : "default",
           "#FIXED"    : "fixed" }

def write_attr(out, attr):
    value = attr.get_default()
    if value == None:
        value = ''
    else:
        value = ' value="%s"' % escape_attr_value(value)

    attrtype = attr.get_type()
    if type(attrtype) == types.ListType:
        out.write('      <attribute name="%s" use="%s"%s>\n' %
                  (attr.get_name(), declmap[attr.get_decl()], value))
        out.write('        <simpleType base="NMTOKEN">\n')        
        for token in attrtype:
            out.write('          <enumeration value="%s"/>\n' % token)
        out.write('        </simpleType>\n')
        out.write('      </attribute>\n')
    else:
        out.write('      <attribute name="%s" type="%s" use="%s"%s/>\n' %
                  (attr.get_name(), attrtype, declmap[attr.get_decl()],
                   value))

def write_attributes(out, elem, attrinfo):
    attrnames = elem.get_attr_list()
    shared = attrinfo.get_shared_attrs_on_elem(elem.get_name()) or []
    for attrname in attrnames:
        if not attrname in shared:
            write_attr(out, elem.get_attr(attrname))
            
    if shared:
        out.write('      <attributeGroup ref="%s">\n' %
                  attrinfo.get_group_name(group))
        
def write_element_type(out, elem, attrinfo):
    cm = elem.get_content_model()
    if cm == ('', [('#PCDATA', '')], ''):
        if elem.get_attr_list() == []:
            out.write('    <simpleType ref="string"/>\n')
        else:
            out.write('    <complexType base="string" derivedBy="extension">\n')
            write_attributes(out, elem, attrinfo)
            out.write('    </complexType>\n')
        return

    content = ''
    if cm == ("", [], ""):
        content = ' content="empty"'
    elif cm != None and cm[1][0][0] == "#PCDATA":
        content = ' content="mixed"'
            
    out.write('    <complexType%s>\n' % content)
    if cm == None:
        out.write('    <any/>\n')
    elif cm != ("", [], ""):
        write_cm(out, cm)
        
    write_attributes(out, elem, attrinfo)
    out.write('    </complexType>\n')
        
def write_cm(out, cm):
    (sep, cps, mod) = cm
    out.write('    <group>\n')

    if sep == '' or sep == ',':
        wrapper = 'sequence'
    elif sep == '|':
        wrapper = 'choice'

    out.write('      <%s>\n' % wrapper)
    for cp in cps:
        if len(cp) == 2:
            (name, mod) = cp
            if name == "#PCDATA":
                continue

            if mod == '?':
                occurs = ' minOccurs="0"'
            elif mod == '*':
                occurs = ' minOccurs="0" maxOccurs="*"'
            elif mod == '+':
                occurs = ' minOccurs="1" maxOccurs="*"'
            else:
                occurs = ''

            out.write('        <element ref="%s"%s>\n' % (name, occurs))
        elif len(cp) == 3:
            write_cm(out, cp)
        else:
            out.write('        <!-- %s -->\n' % (cp,))

    out.write('      <%s>\n' % wrapper)
    
    out.write('    </group>\n')    

# ===== MAIN PROGRAM

# --- Interpreting command-line

if len(sys.argv) < 2 or len(sys.argv) > 3:
    print usage
    sys.exit(1)

infile = sys.argv[1]
if len(sys.argv) == 3:
    outfile = sys.argv[2]
else:
    ext = os.path.splitext(infile)[1]
    outfile = os.path.split(infile)[1]
    outfile = outfile[ : -len(ext)] + ".xsd"

# --- Doing the job

print "\ndtd2schema.py\n"

# Load DTD

print "Loading DTD..."
dtd = xmldtd.load_dtd(infile)

# Find attribute groups

print "Doing reverse-engineering..."
attrinfo = find_attr_groups(dtd)

# Write out schema

print "Writing out schema"
out = open(outfile, "w")

out.write('<?xml version="1.0"?>\n')
out.write('<!--\n')
out.write('  Converted from a DTD by dtd2schema.py, using xmlproc.\n')
out.write('  NOTE: This version is not reliable. It has not been\n')
out.write('  properly checked against the standard (20000407 WD) yet.\n')
out.write('-->\n\n')
out.write('<schema xmlns="http://www.w3.org/1999/XMLSchema">\n\n')

if attrinfo:
    out.write('<!-- ========= ATTRIBUTE GROUP DECLARATIONS ========= -->\n\n')

    for group in attrinfo.get_groups():
        write_attribute_group(out, group, attrinfo)

    out.write("\n")
            
out.write('<!-- ========== ELEMENT DECLARATIONS ========== -->\n\n')

for elemname in dtd.get_elements():
    elem = dtd.get_elem(elemname)
    out.write('  <element name="%s">\n' % elemname)
    write_element_type(out, elem, attrinfo)        
    out.write('  </element>\n\n')

notations = dtd.get_notations()
if notations != []:
    out.write('\n\n<!-- ========== NOTATION DECLARATIONS ========== -->\n\n')

    for notname in notations:
        (pubid, sysid) = dtd.get_notation(notname)
        if sysid == None:
            sysid = ''
        else:
            sysid = ' system="%s"'
        
        out.write('  <notation name="%s" public="%s"%s>\n' %
                  (notname, pubid, sysid))
    
out.write('</schema>\n')
out.close()