# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
#
# Automatically generated by addcopyright.py at 01/29/2013
'''
Created on Dec 25, 2012

@author: Frank
'''
import xml.etree.ElementTree as etree
import re
import types

class XmlObject(object):
    def __init__(self, tag):
        self.__tag_name__ = tag

    def put_attr(self, name, val):
        val = val.strip().strip('\t')
        setattr(self, name + '_', val)

    def put_text(self, val):
        val = val.strip().strip('\n').strip('\t')
        if val == "":
            setattr(self, 'text_', None)
        else:
            setattr(self, 'text_', val)

    def put_node(self, name, val):
        if not hasattr(self, name):
            setattr(self, name, val)
            return

        nodes = getattr(self, name)
        if not isinstance(nodes, types.ListType):
            nodes = []
            old = getattr(self, name)
            nodes.append(old)
            nodes.append(val)
            setattr(self, name, nodes)
        else:
            nodes.append(val)
            setattr(self, name, nodes)

    def get(self, name, default=None):
        if hasattr(self, name):
            val = getattr(self, name)
            if name.endswith('_'):
                return val
            else:
                return val.text_
        else:
            return default

    def __getattr__(self, name):
        if name.endswith('__'):
            n = name[:-1]
            if hasattr(self, n):
                return getattr(self, n)
            else:
                return None
        else:
            e = AttributeError('%s has no attribute %s. missing attribute %s in element <%s>' % (self.__class__.__name__, name, name, self.__tag_name__))
            setattr(e, 'missing_attrib', name)
            setattr(e, 'tag_name', self.__tag_name__)
            raise e


def _loads(node):
    xo = XmlObject(node.tag)
    for key in node.attrib.keys():
        xo.put_attr(key, node.attrib.get(key))
    if node.text:
        xo.put_text(node.text)
    for n in list(node):
        sub_xo = _loads(n)
        xo.put_node(n.tag, sub_xo)
    return xo

def loads(xmlstr):
    xmlstr = re.sub(r'xmlns=".*"', '', xmlstr)
    root = etree.fromstring(xmlstr)
    return _loads(root)