# Copyright (c) 2004 by Intevation GmbH
# Authors:
# Martin Schulze <joey@infodrom.org>
#
# 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

"""
Convenience routines for handling of Document Object Model (DOM)
nodes.

For more information on DOM see <http://www.zytrax.com/tech/dom/guide.html>.

"""

def listChildNodes (node):
    """
    Prints a list of all child DOM nodes for the given node.  This
    function is normally only used for inspection of a DOM tree during
    development.
    """
    print "Node %s has %d children" % (node.nodeName, node.childNodes.length)
    for i in range (node.childNodes.length):
        print "  %d: %s" % (i, node.childNodes[i].nodeName)


def listAttributes (node):
    """
    Prints a list of all DOM attributes for the given node.  This
    function is normally only used for inspection of a DOM tree during
    development.
    """
    print "Node %s has %d attributes" % (node.nodeName, node.attributes.length)
    for key in node.attributes.keys():
        print "  %s=%s" % (key, node.attributes.get(key).nodeValue)


# Can't use node.getElementsByTagName(name) since it traverses the XML
# data recursively and we need hierarchy information as well in order
# to get inheritance of attributes implemented properly.
#
def getElementsByName (node, name):
    """
    Returns a list of child DOM nodes whose nodeName matches given
    string.
    """
    res = []
    for i in range (node.childNodes.length):
        if node.childNodes[i].nodeName == name:
            res.append(node.childNodes[i])
    return res


def getElementByName (node, name):
    """
    Returns the first child DOM node whose nodeName matches given
    string.
    """
    try:
        return getElementsByName (node, name)[0]
    except IndexError:
        return None


