-
Notifications
You must be signed in to change notification settings - Fork 0
/
generate_sample_xml
executable file
·58 lines (45 loc) · 1.42 KB
/
generate_sample_xml
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
#!/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_template = """<?xml version="1.0" encoding="UTF-8"?>
<!-- generated by generate_sample_xml -->
<%s xmlns:%s="%s" xmlns:xnat="http://nrg.wustl.edu/xnat" ID="">
<xnat:subject_ID>xnat_S123456</xnat:subject_ID>
</%s>
"""
progname = os.path.basename(sys.argv[0])
if len(sys.argv) == 1:
print
print 'usage: %s <JSON file>' % progname
print
print 'outputs sample XML 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']
root_tag_name = '%s:%s' % (ns, data['name'])
base_xml = base_xml_template % (root_tag_name, ns, ns_uri, root_tag_name)
doc = xml.dom.minidom.parseString(base_xml)
root_node = doc.getElementsByTagName(root_tag_name)[0]
for element in data['elements']:
xml_el = doc.createElement(element['name'])
if element['type'] == 'xs:integer':
text_node = doc.createTextNode('1')
xml_el.appendChild(text_node)
root_node.appendChild(xml_el)
else:
fmt = '%s: unknown or unhandled type %s\n'
sys.stderr.write(fmt % (progname, element['type']))
sys.exit(1)
print doc.toxml()
sys.exit(0)
# eof