0001"""ElementTree extensions."""
0002
0003__revision__ = "$Rev$"
0004__date__ = "$Date: 2005-02-16 15:43:38 -0500 (Wed, 16 Feb 2005) $"
0005__author__ = "Ryan Tomayko (rtomayko@gmail.com)"
0006__copyright__ = "Copyright 2004-2005, Ryan Tomayko"
0007__license__ = "MIT <http://www.opensource.org/licenses/mit-license.php>"
0008
0009import os
0010
0011import elementtree.ElementTree as ET
0012if not os.environ.get('KID_NOCET'):
0013    try:
0014        from cElementTree import *
0015    except ImportError:
0016        from elementtree.ElementTree import *
0017else:
0018    from elementtree.ElementTree import *
0019
0020def Comment(text=None):
0021    elem = Element(Comment)
0022    elem.text = text
0023    return elem
0024
0025def ProcessingInstruction(target, text=None):
0026    element = Element(ProcessingInstruction)
0027    element.text = target
0028    if text:
0029        element.text = element.text + " " + text
0030    return element
0031
0032def Fragment(text=''):
0033    """Create an XML fragment.
0034
0035    Fragments hold TEXT and children but do not have a tag or attributes.
0036    """
0037    elem = Element(Fragment)
0038    elem.text = text
0039    return elem
0040
0041def namespaces(elem, remove=0):
0042    """Get the namespace declarations for an Element.
0043
0044    This function looks for attributes on the Element provided that have the
0045    following characteristics:
0046
0047       * Begin with 'xmlns:' and have no namespace URI.
0048       * Are named 'xmlns' and have no namespace URI.
0049
0050    The result is a dictionary containing namespace prefix -> URI mappings.
0051    Default namespace attributes result in a key of ''.
0052
0053    If remove is truthful, namespace declaration attributes are removed
0054    from the passed in Element.
0055    
0056    """
0057
0058    names = {}
0059    for k in elem.keys():
0060        if k.startswith('xmlns:'):
0061            names[k[6:]] = elem.get(k)
0062            if remove: del elem.attrib[k]
0063        elif k == 'xmlns':
0064            names[''] = elem.get(k)
0065            if remove: del elem.attrib[k]
0066    return names
0067
0068__all__ = ['Element', 'SubElement', 'Comment', 'ProcessingInstruction',
0069           'Fragment', 'ElementTree', 'QName', 'dump',
0070           'parse', 'tostring', 'namespaces']