Blame python/libxml.py

Packit 423ecb
import libxml2mod
Packit 423ecb
import types
Packit 423ecb
import sys
Packit 423ecb
Packit 423ecb
# The root of all libxml2 errors.
Packit 423ecb
class libxmlError(Exception): pass
Packit 423ecb
Packit 423ecb
# Type of the wrapper class for the C objects wrappers
Packit 423ecb
def checkWrapper(obj):
Packit 423ecb
    try:
Packit 423ecb
        n = type(_obj).__name__
Packit 423ecb
        if n != 'PyCObject' and n != 'PyCapsule':
Packit 423ecb
            return 1
Packit 423ecb
    except:
Packit 423ecb
        return 0
Packit 423ecb
    return 0
Packit 423ecb
Packit 423ecb
#
Packit 423ecb
# id() is sometimes negative ...
Packit 423ecb
#
Packit 423ecb
def pos_id(o):
Packit 423ecb
    i = id(o)
Packit 423ecb
    if (i < 0):
Packit 423ecb
        return (sys.maxsize - i)
Packit 423ecb
    return i
Packit 423ecb
Packit 423ecb
#
Packit 423ecb
# Errors raised by the wrappers when some tree handling failed.
Packit 423ecb
#
Packit 423ecb
class treeError(libxmlError):
Packit 423ecb
    def __init__(self, msg):
Packit 423ecb
        self.msg = msg
Packit 423ecb
    def __str__(self):
Packit 423ecb
        return self.msg
Packit 423ecb
Packit 423ecb
class parserError(libxmlError):
Packit 423ecb
    def __init__(self, msg):
Packit 423ecb
        self.msg = msg
Packit 423ecb
    def __str__(self):
Packit 423ecb
        return self.msg
Packit 423ecb
Packit 423ecb
class uriError(libxmlError):
Packit 423ecb
    def __init__(self, msg):
Packit 423ecb
        self.msg = msg
Packit 423ecb
    def __str__(self):
Packit 423ecb
        return self.msg
Packit 423ecb
Packit 423ecb
class xpathError(libxmlError):
Packit 423ecb
    def __init__(self, msg):
Packit 423ecb
        self.msg = msg
Packit 423ecb
    def __str__(self):
Packit 423ecb
        return self.msg
Packit 423ecb
Packit 423ecb
class ioWrapper:
Packit 423ecb
    def __init__(self, _obj):
Packit 423ecb
        self.__io = _obj
Packit 423ecb
        self._o = None
Packit 423ecb
Packit 423ecb
    def io_close(self):
Packit 423ecb
        if self.__io == None:
Packit 423ecb
            return(-1)
Packit 423ecb
        self.__io.close()
Packit 423ecb
        self.__io = None
Packit 423ecb
        return(0)
Packit 423ecb
Packit 423ecb
    def io_flush(self):
Packit 423ecb
        if self.__io == None:
Packit 423ecb
            return(-1)
Packit 423ecb
        self.__io.flush()
Packit 423ecb
        return(0)
Packit 423ecb
Packit 423ecb
    def io_read(self, len = -1):
Packit 423ecb
        if self.__io == None:
Packit 423ecb
            return(-1)
Packit 423ecb
        try:
Packit 423ecb
            if len < 0:
Packit 423ecb
                ret = self.__io.read()
Packit 423ecb
            else:
Packit 423ecb
                ret = self.__io.read(len)
Packit 423ecb
        except Exception:
Packit 423ecb
            import sys
Packit 423ecb
            e = sys.exc_info()[1]
Packit 423ecb
            print("failed to read from Python:", type(e))
Packit 423ecb
            print("on IO:", self.__io)
Packit 423ecb
            self.__io == None
Packit 423ecb
            return(-1)
Packit 423ecb
Packit 423ecb
        return(ret)
Packit 423ecb
Packit 423ecb
    def io_write(self, str, len = -1):
Packit 423ecb
        if self.__io == None:
Packit 423ecb
            return(-1)
Packit 423ecb
        if len < 0:
Packit 423ecb
            return(self.__io.write(str))
Packit 423ecb
        return(self.__io.write(str, len))
Packit 423ecb
Packit 423ecb
class ioReadWrapper(ioWrapper):
Packit 423ecb
    def __init__(self, _obj, enc = ""):
Packit 423ecb
        ioWrapper.__init__(self, _obj)
Packit 423ecb
        self._o = libxml2mod.xmlCreateInputBuffer(self, enc)
Packit 423ecb
Packit 423ecb
    def __del__(self):
Packit 423ecb
        print("__del__")
Packit 423ecb
        self.io_close()
Packit 423ecb
        if self._o != None:
Packit 423ecb
            libxml2mod.xmlFreeParserInputBuffer(self._o)
Packit 423ecb
        self._o = None
Packit 423ecb
Packit 423ecb
    def close(self):
Packit 423ecb
        self.io_close()
Packit 423ecb
        if self._o != None:
Packit 423ecb
            libxml2mod.xmlFreeParserInputBuffer(self._o)
Packit 423ecb
        self._o = None
Packit 423ecb
Packit 423ecb
class ioWriteWrapper(ioWrapper):
Packit 423ecb
    def __init__(self, _obj, enc = ""):
Packit 423ecb
#        print "ioWriteWrapper.__init__", _obj
Packit 423ecb
        if type(_obj) == type(''):
Packit 423ecb
            print("write io from a string")
Packit 423ecb
            self.o = None
Packit 423ecb
        elif type(_obj).__name__ == 'PyCapsule':
Packit 423ecb
            file = libxml2mod.outputBufferGetPythonFile(_obj)
Packit 423ecb
            if file != None:
Packit 423ecb
                ioWrapper.__init__(self, file)
Packit 423ecb
            else:
Packit 423ecb
                ioWrapper.__init__(self, _obj)
Packit 423ecb
            self._o = _obj
Packit 423ecb
#        elif type(_obj) == types.InstanceType:
Packit 423ecb
#            print(("write io from instance of %s" % (_obj.__class__)))
Packit 423ecb
#            ioWrapper.__init__(self, _obj)
Packit 423ecb
#            self._o = libxml2mod.xmlCreateOutputBuffer(self, enc)
Packit 423ecb
        else:
Packit 423ecb
            file = libxml2mod.outputBufferGetPythonFile(_obj)
Packit 423ecb
            if file != None:
Packit 423ecb
                ioWrapper.__init__(self, file)
Packit 423ecb
            else:
Packit 423ecb
                ioWrapper.__init__(self, _obj)
Packit 423ecb
            self._o = _obj
Packit 423ecb
Packit 423ecb
    def __del__(self):
Packit 423ecb
#        print "__del__"
Packit 423ecb
        self.io_close()
Packit 423ecb
        if self._o != None:
Packit 423ecb
            libxml2mod.xmlOutputBufferClose(self._o)
Packit 423ecb
        self._o = None
Packit 423ecb
Packit 423ecb
    def flush(self):
Packit 423ecb
        self.io_flush()
Packit 423ecb
        if self._o != None:
Packit 423ecb
            libxml2mod.xmlOutputBufferClose(self._o)
Packit 423ecb
        self._o = None
Packit 423ecb
Packit 423ecb
    def close(self):
Packit 423ecb
        self.io_flush()
Packit 423ecb
        if self._o != None:
Packit 423ecb
            libxml2mod.xmlOutputBufferClose(self._o)
Packit 423ecb
        self._o = None
Packit 423ecb
Packit 423ecb
#
Packit 423ecb
# Example of a class to handle SAX events
Packit 423ecb
#
Packit 423ecb
class SAXCallback:
Packit 423ecb
    """Base class for SAX handlers"""
Packit 423ecb
    def startDocument(self):
Packit 423ecb
        """called at the start of the document"""
Packit 423ecb
        pass
Packit 423ecb
Packit 423ecb
    def endDocument(self):
Packit 423ecb
        """called at the end of the document"""
Packit 423ecb
        pass
Packit 423ecb
Packit 423ecb
    def startElement(self, tag, attrs):
Packit 423ecb
        """called at the start of every element, tag is the name of
Packit 423ecb
           the element, attrs is a dictionary of the element's attributes"""
Packit 423ecb
        pass
Packit 423ecb
Packit 423ecb
    def endElement(self, tag):
Packit 423ecb
        """called at the start of every element, tag is the name of
Packit 423ecb
           the element"""
Packit 423ecb
        pass
Packit 423ecb
Packit 423ecb
    def characters(self, data):
Packit 423ecb
        """called when character data have been read, data is the string
Packit 423ecb
           containing the data, multiple consecutive characters() callback
Packit 423ecb
           are possible."""
Packit 423ecb
        pass
Packit 423ecb
Packit 423ecb
    def cdataBlock(self, data):
Packit 423ecb
        """called when CDATA section have been read, data is the string
Packit 423ecb
           containing the data, multiple consecutive cdataBlock() callback
Packit 423ecb
           are possible."""
Packit 423ecb
        pass
Packit 423ecb
Packit 423ecb
    def reference(self, name):
Packit 423ecb
        """called when an entity reference has been found"""
Packit 423ecb
        pass
Packit 423ecb
Packit 423ecb
    def ignorableWhitespace(self, data):
Packit 423ecb
        """called when potentially ignorable white spaces have been found"""
Packit 423ecb
        pass
Packit 423ecb
Packit 423ecb
    def processingInstruction(self, target, data):
Packit 423ecb
        """called when a PI has been found, target contains the PI name and
Packit 423ecb
           data is the associated data in the PI"""
Packit 423ecb
        pass
Packit 423ecb
Packit 423ecb
    def comment(self, content):
Packit 423ecb
        """called when a comment has been found, content contains the comment"""
Packit 423ecb
        pass
Packit 423ecb
Packit 423ecb
    def externalSubset(self, name, externalID, systemID):
Packit 423ecb
        """called when a DOCTYPE declaration has been found, name is the
Packit 423ecb
           DTD name and externalID, systemID are the DTD public and system
Packit 423ecb
           identifier for that DTd if available"""
Packit 423ecb
        pass
Packit 423ecb
Packit 423ecb
    def internalSubset(self, name, externalID, systemID):
Packit 423ecb
        """called when a DOCTYPE declaration has been found, name is the
Packit 423ecb
           DTD name and externalID, systemID are the DTD public and system
Packit 423ecb
           identifier for that DTD if available"""
Packit 423ecb
        pass
Packit 423ecb
Packit 423ecb
    def entityDecl(self, name, type, externalID, systemID, content):
Packit 423ecb
        """called when an ENTITY declaration has been found, name is the
Packit 423ecb
           entity name and externalID, systemID are the entity public and
Packit 423ecb
           system identifier for that entity if available, type indicates
Packit 423ecb
           the entity type, and content reports it's string content"""
Packit 423ecb
        pass
Packit 423ecb
Packit 423ecb
    def notationDecl(self, name, externalID, systemID):
Packit 423ecb
        """called when an NOTATION declaration has been found, name is the
Packit 423ecb
           notation name and externalID, systemID are the notation public and
Packit 423ecb
           system identifier for that notation if available"""
Packit 423ecb
        pass
Packit 423ecb
Packit 423ecb
    def attributeDecl(self, elem, name, type, defi, defaultValue, nameList):
Packit 423ecb
        """called when an ATTRIBUTE definition has been found"""
Packit 423ecb
        pass
Packit 423ecb
Packit 423ecb
    def elementDecl(self, name, type, content):
Packit 423ecb
        """called when an ELEMENT definition has been found"""
Packit 423ecb
        pass
Packit 423ecb
Packit 423ecb
    def entityDecl(self, name, publicId, systemID, notationName):
Packit 423ecb
        """called when an unparsed ENTITY declaration has been found,
Packit 423ecb
           name is the entity name and publicId,, systemID are the entity
Packit 423ecb
           public and system identifier for that entity if available,
Packit 423ecb
           and notationName indicate the associated NOTATION"""
Packit 423ecb
        pass
Packit 423ecb
Packit 423ecb
    def warning(self, msg):
Packit 423ecb
        #print msg
Packit 423ecb
        pass
Packit 423ecb
Packit 423ecb
    def error(self, msg):
Packit 423ecb
        raise parserError(msg)
Packit 423ecb
Packit 423ecb
    def fatalError(self, msg):
Packit 423ecb
        raise parserError(msg)
Packit 423ecb
Packit 423ecb
#
Packit 423ecb
# This class is the ancestor of all the Node classes. It provides
Packit 423ecb
# the basic functionalities shared by all nodes (and handle
Packit 423ecb
# gracefylly the exception), like name, navigation in the tree,
Packit 423ecb
# doc reference, content access and serializing to a string or URI
Packit 423ecb
#
Packit 423ecb
class xmlCore:
Packit 423ecb
    def __init__(self, _obj=None):
Packit 423ecb
        if _obj != None: 
Packit 423ecb
            self._o = _obj;
Packit 423ecb
            return
Packit 423ecb
        self._o = None
Packit 423ecb
Packit 423ecb
    def __eq__(self, other):
Packit 423ecb
        if other == None:
Packit 423ecb
            return False
Packit 423ecb
        ret = libxml2mod.compareNodesEqual(self._o, other._o)
Packit 423ecb
        if ret == None:
Packit 423ecb
            return False
Packit 423ecb
        return ret == True
Packit 423ecb
    def __ne__(self, other):
Packit 423ecb
        if other == None:
Packit 423ecb
            return True
Packit 423ecb
        ret = libxml2mod.compareNodesEqual(self._o, other._o)
Packit 423ecb
        return not ret
Packit 423ecb
    def __hash__(self):
Packit 423ecb
        ret = libxml2mod.nodeHash(self._o)
Packit 423ecb
        return ret
Packit 423ecb
Packit 423ecb
    def __str__(self):
Packit 423ecb
        return self.serialize()
Packit 423ecb
    def get_parent(self):
Packit 423ecb
        ret = libxml2mod.parent(self._o)
Packit 423ecb
        if ret == None:
Packit 423ecb
            return None
Packit 423ecb
        return nodeWrap(ret)
Packit 423ecb
    def get_children(self):
Packit 423ecb
        ret = libxml2mod.children(self._o)
Packit 423ecb
        if ret == None:
Packit 423ecb
            return None
Packit 423ecb
        return nodeWrap(ret)
Packit 423ecb
    def get_last(self):
Packit 423ecb
        ret = libxml2mod.last(self._o)
Packit 423ecb
        if ret == None:
Packit 423ecb
            return None
Packit 423ecb
        return nodeWrap(ret)
Packit 423ecb
    def get_next(self):
Packit 423ecb
        ret = libxml2mod.next(self._o)
Packit 423ecb
        if ret == None:
Packit 423ecb
            return None
Packit 423ecb
        return nodeWrap(ret)
Packit 423ecb
    def get_properties(self):
Packit 423ecb
        ret = libxml2mod.properties(self._o)
Packit 423ecb
        if ret == None:
Packit 423ecb
            return None
Packit 423ecb
        return xmlAttr(_obj=ret)
Packit 423ecb
    def get_prev(self):
Packit 423ecb
        ret = libxml2mod.prev(self._o)
Packit 423ecb
        if ret == None:
Packit 423ecb
            return None
Packit 423ecb
        return nodeWrap(ret)
Packit 423ecb
    def get_content(self):
Packit 423ecb
        return libxml2mod.xmlNodeGetContent(self._o)
Packit 423ecb
    getContent = get_content  # why is this duplicate naming needed ?
Packit 423ecb
    def get_name(self):
Packit 423ecb
        return libxml2mod.name(self._o)
Packit 423ecb
    def get_type(self):
Packit 423ecb
        return libxml2mod.type(self._o)
Packit 423ecb
    def get_doc(self):
Packit 423ecb
        ret = libxml2mod.doc(self._o)
Packit 423ecb
        if ret == None:
Packit 423ecb
            if self.type in ["document_xml", "document_html"]:
Packit 423ecb
                return xmlDoc(_obj=self._o)
Packit 423ecb
            else:
Packit 423ecb
                return None
Packit 423ecb
        return xmlDoc(_obj=ret)
Packit 423ecb
    #
Packit 423ecb
    # Those are common attributes to nearly all type of nodes
Packit 423ecb
    # defined as python2 properties
Packit 423ecb
    # 
Packit 423ecb
    import sys
Packit 423ecb
    if float(sys.version[0:3]) < 2.2:
Packit 423ecb
        def __getattr__(self, attr):
Packit 423ecb
            if attr == "parent":
Packit 423ecb
                ret = libxml2mod.parent(self._o)
Packit 423ecb
                if ret == None:
Packit 423ecb
                    return None
Packit 423ecb
                return nodeWrap(ret)
Packit 423ecb
            elif attr == "properties":
Packit 423ecb
                ret = libxml2mod.properties(self._o)
Packit 423ecb
                if ret == None:
Packit 423ecb
                    return None
Packit 423ecb
                return xmlAttr(_obj=ret)
Packit 423ecb
            elif attr == "children":
Packit 423ecb
                ret = libxml2mod.children(self._o)
Packit 423ecb
                if ret == None:
Packit 423ecb
                    return None
Packit 423ecb
                return nodeWrap(ret)
Packit 423ecb
            elif attr == "last":
Packit 423ecb
                ret = libxml2mod.last(self._o)
Packit 423ecb
                if ret == None:
Packit 423ecb
                    return None
Packit 423ecb
                return nodeWrap(ret)
Packit 423ecb
            elif attr == "next":
Packit 423ecb
                ret = libxml2mod.next(self._o)
Packit 423ecb
                if ret == None:
Packit 423ecb
                    return None
Packit 423ecb
                return nodeWrap(ret)
Packit 423ecb
            elif attr == "prev":
Packit 423ecb
                ret = libxml2mod.prev(self._o)
Packit 423ecb
                if ret == None:
Packit 423ecb
                    return None
Packit 423ecb
                return nodeWrap(ret)
Packit 423ecb
            elif attr == "content":
Packit 423ecb
                return libxml2mod.xmlNodeGetContent(self._o)
Packit 423ecb
            elif attr == "name":
Packit 423ecb
                return libxml2mod.name(self._o)
Packit 423ecb
            elif attr == "type":
Packit 423ecb
                return libxml2mod.type(self._o)
Packit 423ecb
            elif attr == "doc":
Packit 423ecb
                ret = libxml2mod.doc(self._o)
Packit 423ecb
                if ret == None:
Packit 423ecb
                    if self.type == "document_xml" or self.type == "document_html":
Packit 423ecb
                        return xmlDoc(_obj=self._o)
Packit 423ecb
                    else:
Packit 423ecb
                        return None
Packit 423ecb
                return xmlDoc(_obj=ret)
Packit 423ecb
            raise AttributeError(attr)
Packit 423ecb
    else:
Packit 423ecb
        parent = property(get_parent, None, None, "Parent node")
Packit 423ecb
        children = property(get_children, None, None, "First child node")
Packit 423ecb
        last = property(get_last, None, None, "Last sibling node")
Packit 423ecb
        next = property(get_next, None, None, "Next sibling node")
Packit 423ecb
        prev = property(get_prev, None, None, "Previous sibling node")
Packit 423ecb
        properties = property(get_properties, None, None, "List of properies")
Packit 423ecb
        content = property(get_content, None, None, "Content of this node")
Packit 423ecb
        name = property(get_name, None, None, "Node name")
Packit 423ecb
        type = property(get_type, None, None, "Node type")
Packit 423ecb
        doc = property(get_doc, None, None, "The document this node belongs to")
Packit 423ecb
Packit 423ecb
    #
Packit 423ecb
    # Serialization routines, the optional arguments have the following
Packit 423ecb
    # meaning:
Packit 423ecb
    #     encoding: string to ask saving in a specific encoding
Packit 423ecb
    #     indent: if 1 the serializer is asked to indent the output
Packit 423ecb
    #
Packit 423ecb
    def serialize(self, encoding = None, format = 0):
Packit 423ecb
        return libxml2mod.serializeNode(self._o, encoding, format)
Packit 423ecb
    def saveTo(self, file, encoding = None, format = 0):
Packit 423ecb
        return libxml2mod.saveNodeTo(self._o, file, encoding, format)
Packit 423ecb
            
Packit 423ecb
    #
Packit 423ecb
    # Canonicalization routines:
Packit 423ecb
    #
Packit 423ecb
    #   nodes: the node set (tuple or list) to be included in the
Packit 423ecb
    #     canonized image or None if all document nodes should be
Packit 423ecb
    #     included.
Packit 423ecb
    #   exclusive: the exclusive flag (0 - non-exclusive
Packit 423ecb
    #     canonicalization; otherwise - exclusive canonicalization)
Packit 423ecb
    #   prefixes: the list of inclusive namespace prefixes (strings),
Packit 423ecb
    #     or None if there is no inclusive namespaces (only for
Packit 423ecb
    #     exclusive canonicalization, ignored otherwise)
Packit 423ecb
    #   with_comments: include comments in the result (!=0) or not
Packit 423ecb
    #     (==0)
Packit 423ecb
    def c14nMemory(self,
Packit 423ecb
                   nodes=None,
Packit 423ecb
                   exclusive=0,
Packit 423ecb
                   prefixes=None,
Packit 423ecb
                   with_comments=0):
Packit 423ecb
        if nodes:
Packit 423ecb
            nodes = [n._o for n in nodes]
Packit 423ecb
        return libxml2mod.xmlC14NDocDumpMemory(
Packit 423ecb
            self.get_doc()._o,
Packit 423ecb
            nodes,
Packit 423ecb
            exclusive != 0,
Packit 423ecb
            prefixes,
Packit 423ecb
            with_comments != 0)
Packit 423ecb
    def c14nSaveTo(self,
Packit 423ecb
                   file,
Packit 423ecb
                   nodes=None,
Packit 423ecb
                   exclusive=0,
Packit 423ecb
                   prefixes=None,
Packit 423ecb
                   with_comments=0):
Packit 423ecb
        if nodes:
Packit 423ecb
            nodes = [n._o for n in nodes]
Packit 423ecb
        return libxml2mod.xmlC14NDocSaveTo(
Packit 423ecb
            self.get_doc()._o,
Packit 423ecb
            nodes,
Packit 423ecb
            exclusive != 0,
Packit 423ecb
            prefixes,
Packit 423ecb
            with_comments != 0,
Packit 423ecb
            file)
Packit 423ecb
Packit 423ecb
    #
Packit 423ecb
    # Selecting nodes using XPath, a bit slow because the context
Packit 423ecb
    # is allocated/freed every time but convenient.
Packit 423ecb
    #
Packit 423ecb
    def xpathEval(self, expr):
Packit 423ecb
        doc = self.doc
Packit 423ecb
        if doc == None:
Packit 423ecb
            return None
Packit 423ecb
        ctxt = doc.xpathNewContext()
Packit 423ecb
        ctxt.setContextNode(self)
Packit 423ecb
        res = ctxt.xpathEval(expr)
Packit 423ecb
        ctxt.xpathFreeContext()
Packit 423ecb
        return res
Packit 423ecb
Packit 423ecb
#    #
Packit 423ecb
#    # Selecting nodes using XPath, faster because the context
Packit 423ecb
#    # is allocated just once per xmlDoc.
Packit 423ecb
#    #
Packit 423ecb
#    # Removed: DV memleaks c.f. #126735
Packit 423ecb
#    #
Packit 423ecb
#    def xpathEval2(self, expr):
Packit 423ecb
#        doc = self.doc
Packit 423ecb
#        if doc == None:
Packit 423ecb
#            return None
Packit 423ecb
#        try:
Packit 423ecb
#            doc._ctxt.setContextNode(self)
Packit 423ecb
#        except:
Packit 423ecb
#            doc._ctxt = doc.xpathNewContext()
Packit 423ecb
#            doc._ctxt.setContextNode(self)
Packit 423ecb
#        res = doc._ctxt.xpathEval(expr)
Packit 423ecb
#        return res
Packit 423ecb
    def xpathEval2(self, expr):
Packit 423ecb
        return self.xpathEval(expr)
Packit 423ecb
Packit 423ecb
    # Remove namespaces
Packit 423ecb
    def removeNsDef(self, href):
Packit 423ecb
        """
Packit 423ecb
        Remove a namespace definition from a node.  If href is None,
Packit 423ecb
        remove all of the ns definitions on that node.  The removed
Packit 423ecb
        namespaces are returned as a linked list.
Packit 423ecb
Packit 423ecb
        Note: If any child nodes referred to the removed namespaces,
Packit 423ecb
        they will be left with dangling links.  You should call
Packit 423ecb
        renconciliateNs() to fix those pointers.
Packit 423ecb
Packit 423ecb
        Note: This method does not free memory taken by the ns
Packit 423ecb
        definitions.  You will need to free it manually with the
Packit 423ecb
        freeNsList() method on the returns xmlNs object.
Packit 423ecb
        """
Packit 423ecb
Packit 423ecb
        ret = libxml2mod.xmlNodeRemoveNsDef(self._o, href)
Packit 423ecb
        if ret is None:return None
Packit 423ecb
        __tmp = xmlNs(_obj=ret)
Packit 423ecb
        return __tmp
Packit 423ecb
Packit 423ecb
    # support for python2 iterators
Packit 423ecb
    def walk_depth_first(self):
Packit 423ecb
        return xmlCoreDepthFirstItertor(self)
Packit 423ecb
    def walk_breadth_first(self):
Packit 423ecb
        return xmlCoreBreadthFirstItertor(self)
Packit 423ecb
    __iter__ = walk_depth_first
Packit 423ecb
Packit 423ecb
    def free(self):
Packit 423ecb
        try:
Packit 423ecb
            self.doc._ctxt.xpathFreeContext()
Packit 423ecb
        except:
Packit 423ecb
            pass
Packit 423ecb
        libxml2mod.xmlFreeDoc(self._o)
Packit 423ecb
Packit 423ecb
Packit 423ecb
#
Packit 423ecb
# implements the depth-first iterator for libxml2 DOM tree
Packit 423ecb
#
Packit 423ecb
class xmlCoreDepthFirstItertor:
Packit 423ecb
    def __init__(self, node):
Packit 423ecb
        self.node = node
Packit 423ecb
        self.parents = []
Packit 423ecb
    def __iter__(self):
Packit 423ecb
        return self
Packit 423ecb
    def __next__(self):
Packit 423ecb
        while 1:
Packit 423ecb
            if self.node:
Packit 423ecb
                ret = self.node
Packit 423ecb
                self.parents.append(self.node)
Packit 423ecb
                self.node = self.node.children
Packit 423ecb
                return ret
Packit 423ecb
            try:
Packit 423ecb
                parent = self.parents.pop()
Packit 423ecb
            except IndexError:
Packit 423ecb
                raise StopIteration
Packit 423ecb
            self.node = parent.next
Packit 423ecb
    next = __next__
Packit 423ecb
Packit 423ecb
#
Packit 423ecb
# implements the breadth-first iterator for libxml2 DOM tree
Packit 423ecb
#
Packit 423ecb
class xmlCoreBreadthFirstItertor:
Packit 423ecb
    def __init__(self, node):
Packit 423ecb
        self.node = node
Packit 423ecb
        self.parents = []
Packit 423ecb
    def __iter__(self):
Packit 423ecb
        return self
Packit 423ecb
    def __next__(self):
Packit 423ecb
        while 1:
Packit 423ecb
            if self.node:
Packit 423ecb
                ret = self.node
Packit 423ecb
                self.parents.append(self.node)
Packit 423ecb
                self.node = self.node.next
Packit 423ecb
                return ret
Packit 423ecb
            try:
Packit 423ecb
                parent = self.parents.pop()
Packit 423ecb
            except IndexError:
Packit 423ecb
                raise StopIteration
Packit 423ecb
            self.node = parent.children
Packit 423ecb
    next = __next__
Packit 423ecb
Packit 423ecb
#
Packit 423ecb
# converters to present a nicer view of the XPath returns
Packit 423ecb
#
Packit 423ecb
def nodeWrap(o):
Packit 423ecb
    # TODO try to cast to the most appropriate node class
Packit 423ecb
    name = libxml2mod.type(o)
Packit 423ecb
    if name == "element" or name == "text":
Packit 423ecb
        return xmlNode(_obj=o)
Packit 423ecb
    if name == "attribute":
Packit 423ecb
        return xmlAttr(_obj=o)
Packit 423ecb
    if name[0:8] == "document":
Packit 423ecb
        return xmlDoc(_obj=o)
Packit 423ecb
    if name == "namespace":
Packit 423ecb
        return xmlNs(_obj=o)
Packit 423ecb
    if name == "elem_decl":
Packit 423ecb
        return xmlElement(_obj=o)
Packit 423ecb
    if name == "attribute_decl":
Packit 423ecb
        return xmlAttribute(_obj=o)
Packit 423ecb
    if name == "entity_decl":
Packit 423ecb
        return xmlEntity(_obj=o)
Packit 423ecb
    if name == "dtd":
Packit 423ecb
        return xmlDtd(_obj=o)
Packit 423ecb
    return xmlNode(_obj=o)
Packit 423ecb
Packit 423ecb
def xpathObjectRet(o):
Packit 423ecb
    otype = type(o)
Packit 423ecb
    if otype == type([]):
Packit 423ecb
        ret = list(map(xpathObjectRet, o))
Packit 423ecb
        return ret
Packit 423ecb
    elif otype == type(()):
Packit 423ecb
        ret = list(map(xpathObjectRet, o))
Packit 423ecb
        return tuple(ret)
Packit 423ecb
    elif otype == type('') or otype == type(0) or otype == type(0.0):
Packit 423ecb
        return o
Packit 423ecb
    else:
Packit 423ecb
        return nodeWrap(o)
Packit 423ecb
Packit 423ecb
#
Packit 423ecb
# register an XPath function
Packit 423ecb
#
Packit 423ecb
def registerXPathFunction(ctxt, name, ns_uri, f):
Packit 423ecb
    ret = libxml2mod.xmlRegisterXPathFunction(ctxt, name, ns_uri, f)
Packit 423ecb
Packit 423ecb
#
Packit 423ecb
# For the xmlTextReader parser configuration
Packit 423ecb
#
Packit 423ecb
PARSER_LOADDTD=1
Packit 423ecb
PARSER_DEFAULTATTRS=2
Packit 423ecb
PARSER_VALIDATE=3
Packit 423ecb
PARSER_SUBST_ENTITIES=4
Packit 423ecb
Packit 423ecb
#
Packit 423ecb
# For the error callback severities
Packit 423ecb
#
Packit 423ecb
PARSER_SEVERITY_VALIDITY_WARNING=1
Packit 423ecb
PARSER_SEVERITY_VALIDITY_ERROR=2
Packit 423ecb
PARSER_SEVERITY_WARNING=3
Packit 423ecb
PARSER_SEVERITY_ERROR=4
Packit 423ecb
Packit 423ecb
#
Packit 423ecb
# register the libxml2 error handler
Packit 423ecb
#
Packit 423ecb
def registerErrorHandler(f, ctx):
Packit 423ecb
    """Register a Python written function to for error reporting.
Packit 423ecb
       The function is called back as f(ctx, error). """
Packit 423ecb
    import sys
Packit 423ecb
    if 'libxslt' not in sys.modules:
Packit 423ecb
        # normal behaviour when libxslt is not imported
Packit 423ecb
        ret = libxml2mod.xmlRegisterErrorHandler(f,ctx)
Packit 423ecb
    else:
Packit 423ecb
        # when libxslt is already imported, one must
Packit 423ecb
        # use libxst's error handler instead
Packit 423ecb
        import libxslt
Packit 423ecb
        ret = libxslt.registerErrorHandler(f,ctx)
Packit 423ecb
    return ret
Packit 423ecb
Packit 423ecb
class parserCtxtCore:
Packit 423ecb
Packit 423ecb
    def __init__(self, _obj=None):
Packit 423ecb
        if _obj != None: 
Packit 423ecb
            self._o = _obj;
Packit 423ecb
            return
Packit 423ecb
        self._o = None
Packit 423ecb
Packit 423ecb
    def __del__(self):
Packit 423ecb
        if self._o != None:
Packit 423ecb
            libxml2mod.xmlFreeParserCtxt(self._o)
Packit 423ecb
        self._o = None
Packit 423ecb
Packit 423ecb
    def setErrorHandler(self,f,arg):
Packit 423ecb
        """Register an error handler that will be called back as
Packit 423ecb
           f(arg,msg,severity,reserved).
Packit 423ecb
           
Packit 423ecb
           @reserved is currently always None."""
Packit 423ecb
        libxml2mod.xmlParserCtxtSetErrorHandler(self._o,f,arg)
Packit 423ecb
Packit 423ecb
    def getErrorHandler(self):
Packit 423ecb
        """Return (f,arg) as previously registered with setErrorHandler
Packit 423ecb
           or (None,None)."""
Packit 423ecb
        return libxml2mod.xmlParserCtxtGetErrorHandler(self._o)
Packit 423ecb
Packit 423ecb
    def addLocalCatalog(self, uri):
Packit 423ecb
        """Register a local catalog with the parser"""
Packit 423ecb
        return libxml2mod.addLocalCatalog(self._o, uri)
Packit 423ecb
    
Packit 423ecb
Packit 423ecb
class ValidCtxtCore:
Packit 423ecb
Packit 423ecb
    def __init__(self, *args, **kw):
Packit 423ecb
        pass
Packit 423ecb
Packit 423ecb
    def setValidityErrorHandler(self, err_func, warn_func, arg=None):
Packit 423ecb
        """
Packit 423ecb
        Register error and warning handlers for DTD validation.
Packit 423ecb
        These will be called back as f(msg,arg)
Packit 423ecb
        """
Packit 423ecb
        libxml2mod.xmlSetValidErrors(self._o, err_func, warn_func, arg)
Packit 423ecb
    
Packit 423ecb
Packit 423ecb
class SchemaValidCtxtCore:
Packit 423ecb
Packit 423ecb
    def __init__(self, *args, **kw):
Packit 423ecb
        pass
Packit 423ecb
Packit 423ecb
    def setValidityErrorHandler(self, err_func, warn_func, arg=None):
Packit 423ecb
        """
Packit 423ecb
        Register error and warning handlers for Schema validation.
Packit 423ecb
        These will be called back as f(msg,arg)
Packit 423ecb
        """
Packit 423ecb
        libxml2mod.xmlSchemaSetValidErrors(self._o, err_func, warn_func, arg)
Packit 423ecb
Packit 423ecb
Packit 423ecb
class relaxNgValidCtxtCore:
Packit 423ecb
Packit 423ecb
    def __init__(self, *args, **kw):
Packit 423ecb
        pass
Packit 423ecb
Packit 423ecb
    def setValidityErrorHandler(self, err_func, warn_func, arg=None):
Packit 423ecb
        """
Packit 423ecb
        Register error and warning handlers for RelaxNG validation.
Packit 423ecb
        These will be called back as f(msg,arg)
Packit 423ecb
        """
Packit 423ecb
        libxml2mod.xmlRelaxNGSetValidErrors(self._o, err_func, warn_func, arg)
Packit 423ecb
Packit 423ecb
    
Packit 423ecb
def _xmlTextReaderErrorFunc(xxx_todo_changeme,msg,severity,locator):
Packit 423ecb
    """Intermediate callback to wrap the locator"""
Packit 423ecb
    (f,arg) = xxx_todo_changeme
Packit 423ecb
    return f(arg,msg,severity,xmlTextReaderLocator(locator))
Packit 423ecb
Packit 423ecb
class xmlTextReaderCore:
Packit 423ecb
Packit 423ecb
    def __init__(self, _obj=None):
Packit 423ecb
        self.input = None
Packit 423ecb
        if _obj != None:self._o = _obj;return
Packit 423ecb
        self._o = None
Packit 423ecb
Packit 423ecb
    def __del__(self):
Packit 423ecb
        if self._o != None:
Packit 423ecb
            libxml2mod.xmlFreeTextReader(self._o)
Packit 423ecb
        self._o = None
Packit 423ecb
Packit 423ecb
    def SetErrorHandler(self,f,arg):
Packit 423ecb
        """Register an error handler that will be called back as
Packit 423ecb
           f(arg,msg,severity,locator)."""
Packit 423ecb
        if f is None:
Packit 423ecb
            libxml2mod.xmlTextReaderSetErrorHandler(\
Packit 423ecb
                self._o,None,None)
Packit 423ecb
        else:
Packit 423ecb
            libxml2mod.xmlTextReaderSetErrorHandler(\
Packit 423ecb
                self._o,_xmlTextReaderErrorFunc,(f,arg))
Packit 423ecb
Packit 423ecb
    def GetErrorHandler(self):
Packit 423ecb
        """Return (f,arg) as previously registered with setErrorHandler
Packit 423ecb
           or (None,None)."""
Packit 423ecb
        f,arg = libxml2mod.xmlTextReaderGetErrorHandler(self._o)
Packit 423ecb
        if f is None:
Packit 423ecb
            return None,None
Packit 423ecb
        else:
Packit 423ecb
            # assert f is _xmlTextReaderErrorFunc
Packit 423ecb
            return arg
Packit 423ecb
Packit 423ecb
#
Packit 423ecb
# The cleanup now goes though a wrapper in libxml.c
Packit 423ecb
#
Packit 423ecb
def cleanupParser():
Packit 423ecb
    libxml2mod.xmlPythonCleanupParser()
Packit 423ecb
Packit 423ecb
#
Packit 423ecb
# The interface to xmlRegisterInputCallbacks.
Packit 423ecb
# Since this API does not allow to pass a data object along with
Packit 423ecb
# match/open callbacks, it is necessary to maintain a list of all
Packit 423ecb
# Python callbacks.
Packit 423ecb
#
Packit 423ecb
__input_callbacks = []
Packit 423ecb
def registerInputCallback(func):
Packit 423ecb
    def findOpenCallback(URI):
Packit 423ecb
        for cb in reversed(__input_callbacks):
Packit 423ecb
            o = cb(URI)
Packit 423ecb
            if o is not None:
Packit 423ecb
                return o
Packit 423ecb
    libxml2mod.xmlRegisterInputCallback(findOpenCallback)
Packit 423ecb
    __input_callbacks.append(func)
Packit 423ecb
Packit 423ecb
def popInputCallbacks():
Packit 423ecb
    # First pop python-level callbacks, when no more available - start
Packit 423ecb
    # popping built-in ones.
Packit 423ecb
    if len(__input_callbacks) > 0:
Packit 423ecb
        __input_callbacks.pop()
Packit 423ecb
    if len(__input_callbacks) == 0:
Packit 423ecb
        libxml2mod.xmlUnregisterInputCallback()
Packit 423ecb
Packit 423ecb
# WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING
Packit 423ecb
#
Packit 423ecb
# Everything before this line comes from libxml.py 
Packit 423ecb
# Everything after this line is automatically generated
Packit 423ecb
#
Packit 423ecb
# WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING
Packit 423ecb