-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerate_schema
executable file
·84 lines (68 loc) · 2.42 KB
/
generate_schema
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
#!/usr/bin/python
# Copyright (c) 2011 Christian Haselgrove
# BSD License: http://www.opensource.org/licenses/bsd-license.php
import sys
import os
import json
import xml.dom.minidom
base_xml = """<?xml version="1.0" encoding="UTF-8"?>
<!-- generated by generate_schema -->
<xs:schema xmlns:xnat="http://nrg.wustl.edu/xnat" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:import namespace="http://nrg.wustl.edu/xnat" schemaLocation="../xnat/xnat.xsd"/>
<xs:element/>
<xs:complexType>
<xs:complexContent>
<xs:extension>
<xs:sequence>
</xs:sequence>
</xs:extension>
</xs:complexContent>
</xs:complexType>
</xs:schema>
"""
progname = os.path.basename(sys.argv[0])
if len(sys.argv) == 1:
print
print 'usage: %s <JSON file>' % progname
print
print 'outputs XSD for a custom XNAT data type'
print
sys.exit(1)
try:
fo = open(sys.argv[1])
except Exception, data:
sys.stderr.write('%s: %s\n' % (progname, str(data)))
sys.exit(1)
data = json.load(fo)
(ns, ns_uri) = data['namespace']
doc = xml.dom.minidom.parseString(base_xml)
schema_el = doc.getElementsByTagName('xs:schema')[0]
schema_el.setAttribute('xmlns:%s' % ns, ns_uri)
schema_el.setAttribute('targetNamespace', ns_uri)
element_el = doc.getElementsByTagName('xs:element')[0]
element_el.setAttribute('name', data['name'])
element_el.setAttribute('type', '%s:%s' % (ns, data['type']))
complex_type_el = doc.getElementsByTagName('xs:complexType')[0]
complex_type_el.setAttribute('name', data['type'])
extension_el = doc.getElementsByTagName('xs:extension')[0]
extension_el.setAttribute('base', data['base'])
sequence_el = doc.getElementsByTagName('xs:sequence')[0]
for element in data['elements']:
xml_el = doc.createElement('xs:element')
xml_el.setAttribute('name', element['name'])
xml_el.setAttribute('type', element['type'])
if element.has_key('minOccurs'):
xml_el.setAttribute('minOccurs', element['minOccurs'])
if element.has_key('maxOccurs'):
xml_el.setAttribute('maxOccurs', element['maxOccurs'])
if element.has_key('documentation'):
annot_node = doc.createElement('xs:annotation')
doc_node = doc.createElement('xs:documentation')
text_node = doc.createTextNode(element['documentation'])
doc_node.appendChild(text_node)
annot_node.appendChild(doc_node)
xml_el.appendChild(annot_node)
sequence_el.appendChild(xml_el)
print doc.toxml()
sys.exit(0)
# eof