cleaner xml file handling
[sfa.git] / rspec / parse2.py
1 import xml.dom.minidom
2
3 sample_xml_file = 'sample_rspec.xml'
4 f = open(sample_xml_file, 'r')
5 lines = f.readlines()
6 xml = ""
7 for line in lines:
8     xml += line.replace('\n', '',).repalce('\t', '').strip()
9     
10 dom = xml.dom.minidom.parseString(xml)
11
12 def getText(nodelist):
13     rc = ""
14     for node in nodelist:
15         if node.nodeType == node.TEXT_NODE:
16             rc = rc + node.data
17     return rc
18
19 def handleRspec(rspec):
20     # create rspec dict
21     rdict = {}
22     tempdict = {}    
23     # loop through each network element 
24     for i in rspec.getElementsByTagName("NetSpec"):
25         # handle networks call
26         tempdic[i] = (handleNetworks(rspec.getElementsByTagName("NetSpec")[i]))
27     # append the temp dict
28     rdict['networks'] = tempdic
29     return rdict
30
31 def handleIfs(interf):
32     # create if dict
33     ifdict = {}
34     # loop through attribs and put key value pair into array
35     for i in interf.attributes:
36         a = node.attributes[i]
37         ifdict[a.name] = a.value
38         
39     return ifdict
40
41 def handleNodes(node):
42     # create node dict
43     nodict = {}
44     # loop through attribs and put key value pair into array
45     for i in node.attributes:
46         a = node.attributes[i]
47         nodict[a.name] = a.value
48         
49     # loop through each IF element
50     for i in node.getElementsByTagName("IfSpec"):
51         # handle ifs
52         tempd[i] = handleIfs(node.getElementByTagName("IfSpec")[i])
53     # append temp dict
54     nodict['ifs'] = tempd
55     return nodict
56
57 def handleNetworks(network):
58     # create network dict
59     ndict = {'name':network.nodeName}
60     # loop through each node element
61     for i in network.getElementsByTagName:
62         # handle nodes
63         tempdict[i] = handleNodes(network.getElementsByTagName("NodeSpec")[i])
64     # append temp dict
65     ndict['nodes'] = tempdict
66     return ndict
67
68 def handleTest(slices):
69     for slide in slices:
70         sdict = slice.getElementsByTagName("slices")[0]
71         print "<p>%s</p>" % getText(slice.childNodes)
72
73 handleRspec(dom)
74