-
Notifications
You must be signed in to change notification settings - Fork 12
/
convertyaml_map.py
executable file
·177 lines (146 loc) · 4.55 KB
/
convertyaml_map.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
#!/usr/bin/env python
"""
Sample code to convert YAML to XML and XML to YAML using a canonical
form.
The canonical YAML representation of an XML element is a
dictionary (mapping) containing the following key/value pairs:
(1) "name" (required) -- a string.
(2) "attributes" (optional) -- a dictionary (mapping) of name/value
pairs.
(3) "text" (optional) -- a string.
(4) "children" (optional) -- a sequence of dictionaries (mappings).
For usage information, type:
python convertyaml_map.py
Usage: python convertyaml_map.py <option> <in_file>
Options:
-y2x Convert YAML file to XML document.
-x2y Convert XML document to YAML.
Requirements:
PyXML
PyYaml
"""
import sys, string, re, types
import yaml
from xml.dom import minidom
from xml.dom import Node
#
# Convert a YAML file to XML and write it to stdout.
#
def convertYaml2Xml(inFileName):
inobj = yaml.loadFile(inFileName)
out = []
level = 0
convertYaml2XmlAux(inobj, level, out)
outStr = "".join(out)
sys.stdout.write(outStr)
def convertYaml2XmlAux(inobj, level, out):
for obj in inobj:
if type(obj) == types.DictType and \
obj.has_key('name'):
name = obj['name']
attributes = None
if obj.has_key('attributes'):
attributes = obj['attributes']
text = None
if obj.has_key('text'):
text = obj['text']
children = None
if obj.has_key('children'):
children = obj['children']
addLevel(level, out)
out.append('<%s' % name)
if attributes:
for key in attributes:
out.append(' %s="%s"' % (key, attributes[key]))
if not (children or text):
out.append('/>\n')
else:
if children:
out.append('>\n')
else:
out.append('>')
if text:
out.append(text)
if children:
convertYaml2XmlAux(children, level + 1, out)
addLevel(level, out)
out.append('</%s>\n' % name)
#
# Convert an XML document (file) to YAML and write it to stdout.
#
def convertXml2Yaml(inFileName):
doc = minidom.parse(inFileName)
root = doc.childNodes[0]
# Convert the DOM tree into "YAML-able" data structures.
out = convertXml2YamlAux(root)
# Ask YAML to dump the data structures to a string.
outStr = yaml.dump(out)
# Write the string to stdout.
sys.stdout.write(outStr)
def convertXml2YamlAux(obj):
objDict = {}
# Add the element name.
objDict['name'] = obj.nodeName
# Convert the attributes.
attrs = obj.attributes
if attrs.length > 0:
attrDict = {}
for idx in range(attrs.length):
attr = attrs.item(idx)
attrDict[attr.name] = attr.value
objDict['attributes'] = attrDict
# Convert the text.
text = []
for child in obj.childNodes:
if child.nodeType == Node.TEXT_NODE and \
not isAllWhiteSpace(child.nodeValue):
text.append(child.nodeValue)
if text:
textStr = "".join(text)
objDict['text'] = textStr
# Convert the children.
children = []
for child in obj.childNodes:
if child.nodeType == Node.ELEMENT_NODE:
obj = convertXml2YamlAux(child)
children.append(obj)
if children:
objDict['children'] = children
return objDict
#
# Utility functions.
#
def addLevel(level, out):
for idx in range(level):
out.append(' ')
NonWhiteSpacePattern = re.compile('\S')
def isAllWhiteSpace(text):
if NonWhiteSpacePattern.search(text):
return 0
return 1
USAGE_TEXT = """
Convert a file from YAML to XML or XML to YAML and write it to stdout.
Usage: python convertyaml_map.py <option> <in_file>
Options:
-y2x Convert YAML file to XML document.
-x2y Convert XML document to YAML.
"""
def usage():
print USAGE_TEXT
sys.exit(-1)
def main():
args = sys.argv[1:]
if len(args) != 2:
usage()
option = args[0]
inFileName = args[1]
if option == '-y2x':
convertYaml2Xml(inFileName)
elif option == '-x2y':
convertXml2Yaml(inFileName)
else:
usage()
if __name__ == '__main__':
main()
#import pdb
#pdb.run('main()')