#
# $Id: alcxmlparser.py 431 2006-04-02 02:10:02Z AdamJohnso $
#
#    Copyright (C) 2005-2006  Alcugs pyprp Project Team
#    See the file AUTHORS for more info about the team
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
#    Please see the file COPYING for the full license.
#    Please see the file DISCLAIMER for more details, before doing nothing.
#

import xml.parsers.expat as xmlp

class alcpnode:
    def __init__(self,name,attrs):
        self.name=name
        self.attrs=attrs
        self.data=""


class alcXMLParser:
    def __init__(self):
        self.stack=[]
        self.current=None


    def start_element(self,name,attrs):
        print "Start element:", name, attrs
        if self.current==None:
            self.current=self
        node=alcpnode(name,attrs)
        try:
            var=getattr(self.current,"x" + name)
            var.append(node)
        except AttributeError:
            setattr(self.current,"x" + name.lower(),[node,])
        self.current=node
        self.stack.append(node)


    def end_element(self,name):
        print "End element", name
        if self.current!=None:
            self.stack.remove(self.current)
            if len(self.stack)>0:
                self.current=self.stack[len(self.stack)-1]
            else:
                self.current=None


    def char_data(self,data):
        print "Character data:", repr(data)
        self.current.data = self.current.data + repr(data)


    def parse(self,input):
        p = xmlp.ParserCreate()
        p.StartElementHandler = self.start_element
        p.EndElementHandler = self.end_element
        p.CharacterDataHandler = self.char_data
        p.Parse(input,1)

