I am attempting to parse some xml data and put the grouped data into it's own specific list.
Basically the data looks like this..
<flow-session junos:style="brief">
<session-identifier>42598</session-identifier>
<flow-information junos:style="brief">
<direction>In</direction>
</flow-information>
<flow-information junos:style="brief">
<direction>Out</direction>
</flow-information>
</flow-session>
That will be repeated a couple of times for my example.
Now I want to grab everything between and and toss that into a list. Then once that is completed I want to add that list to another list (or database down the road a bit).
My problem is with the code I currently have I am tossing everything into one massive list, then for each flow-session I am adding it to the big list. So it looks like I am not parsing the xml data correctly in regards to where to start and where to stop..
If you can provide any suggestions or insight I'd greatly appreciate it. Code is below.
edit Not sure why code is coming out unformatted. Shows up fine in edit.
import sys, string, re
from xml.sax import saxutils, handler, make_parser
session_lst = list()
session_id = list()
from xml.sax import saxutils, handler, make_parser
class SessionHandler(handler.ContentHandler):
xmlname = ""
def __init__(*args,**kwargs):
handler.ContentHandler.__init__(*args,**kwargs)
args[0].go = False
def startElement(self, name, attrs):
self.xmlname = name
if name == 'flow-session':
self.go = True
def characters(self, content):
if content != '\n' and re.search(" ", content) == None:
#print("XML NAME:", self.xmlname)
#print("XML CONTENT:", content)
if self.go == True:
xmldata = self.xmlname+":"+content
session_id.append(xmldata)
def endElement(self, name):
handler.ContentHandler.endElement(self,name)
if name == 'flow-session':
self.go = False
session_lst.append(session_id)
parser = make_parser()
curHandler = SessionHandler()
parser.setContentHandler(curHandler)
parser.parse(open('session4.xml'))
for list in session_lst:
print(list)
print('*'*72)
print('*'*72)