⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 libxml.py

📁 libxml,在UNIX/LINUX下非常重要的一个库,为XML相关应用提供方便.目前上载的是最新版本,若要取得最新版本,请参考里面的readme.
💻 PY
📖 第 1 页 / 共 2 页
字号:
import libxml2modimport types# The root of all libxml2 errors.class libxmlError(Exception): pass## Errors raised by the wrappers when some tree handling failed.#class treeError(libxmlError):    def __init__(self, msg):        self.msg = msg    def __str__(self):        return self.msgclass parserError(libxmlError):    def __init__(self, msg):        self.msg = msg    def __str__(self):        return self.msgclass uriError(libxmlError):    def __init__(self, msg):        self.msg = msg    def __str__(self):        return self.msgclass xpathError(libxmlError):    def __init__(self, msg):        self.msg = msg    def __str__(self):        return self.msgclass ioWrapper:    def __init__(self, _obj):        self.__io = _obj        self._o = None    def io_close(self):        if self.__io == None:            return(-1)        self.__io.close()        self.__io = None        return(0)    def io_flush(self):        if self.__io == None:            return(-1)        self.__io.flush()        return(0)    def io_read(self, len = -1):        if self.__io == None:            return(-1)        if len < 0:            return(self.__io.read())        return(self.__io.read(len))    def io_write(self, str, len = -1):        if self.__io == None:            return(-1)        if len < 0:            return(self.__io.write(str))        return(self.__io.write(str, len))class ioReadWrapper(ioWrapper):    def __init__(self, _obj, enc = ""):        ioWrapper.__init__(self, _obj)        self._o = libxml2mod.xmlCreateInputBuffer(self, enc)    def __del__(self):        print "__del__"        self.io_close()        if self._o != None:            libxml2mod.xmlFreeParserInputBuffer(self._o)        self._o = None    def close(self):        self.io_close()        if self._o != None:            libxml2mod.xmlFreeParserInputBuffer(self._o)        self._o = Noneclass ioWriteWrapper(ioWrapper):    def __init__(self, _obj, enc = ""):#        print "ioWriteWrapper.__init__", _obj        if type(_obj) == type(''):            print "write io from a string"            self.o = None        elif type(_obj) == types.InstanceType:            print "write io from instance of %s" % (_obj.__class__)            ioWrapper.__init__(self, _obj)            self._o = libxml2mod.xmlCreateOutputBuffer(self, enc)        else:            file = libxml2mod.outputBufferGetPythonFile(_obj)            if file != None:                ioWrapper.__init__(self, file)            else:                ioWrapper.__init__(self, _obj)            self._o = _obj    def __del__(self):#        print "__del__"        self.io_close()        if self._o != None:            libxml2mod.xmlOutputBufferClose(self._o)        self._o = None    def flush(self):        self.io_flush()        if self._o != None:            libxml2mod.xmlOutputBufferClose(self._o)        self._o = None    def close(self):        self.io_flush()        if self._o != None:            libxml2mod.xmlOutputBufferClose(self._o)        self._o = None## Example of a class to handle SAX events#class SAXCallback:    """Base class for SAX handlers"""    def startDocument(self):        """called at the start of the document"""        pass    def endDocument(self):        """called at the end of the document"""        pass    def startElement(self, tag, attrs):        """called at the start of every element, tag is the name of           the element, attrs is a dictionary of the element's attributes"""        pass    def endElement(self, tag):        """called at the start of every element, tag is the name of           the element"""        pass    def characters(self, data):        """called when character data have been read, data is the string           containing the data, multiple consecutive characters() callback           are possible."""        pass    def cdataBlock(self, data):        """called when CDATA section have been read, data is the string           containing the data, multiple consecutive cdataBlock() callback           are possible."""        pass    def reference(self, name):        """called when an entity reference has been found"""        pass    def ignorableWhitespace(self, data):        """called when potentially ignorable white spaces have been found"""        pass    def processingInstruction(self, target, data):        """called when a PI has been found, target contains the PI name and           data is the associated data in the PI"""        pass    def comment(self, content):        """called when a comment has been found, content contains the comment"""        pass    def externalSubset(self, name, externalID, systemID):        """called when a DOCTYPE declaration has been found, name is the           DTD name and externalID, systemID are the DTD public and system           identifier for that DTd if available"""        pass    def internalSubset(self, name, externalID, systemID):        """called when a DOCTYPE declaration has been found, name is the           DTD name and externalID, systemID are the DTD public and system           identifier for that DTD if available"""        pass    def entityDecl(self, name, type, externalID, systemID, content):        """called when an ENTITY declaration has been found, name is the           entity name and externalID, systemID are the entity public and           system identifier for that entity if available, type indicates           the entity type, and content reports it's string content"""        pass    def notationDecl(self, name, externalID, systemID):        """called when an NOTATION declaration has been found, name is the           notation name and externalID, systemID are the notation public and           system identifier for that notation if available"""        pass    def attributeDecl(self, elem, name, type, defi, defaultValue, nameList):        """called when an ATTRIBUTE definition has been found"""        pass    def elementDecl(self, name, type, content):        """called when an ELEMENT definition has been found"""        pass    def entityDecl(self, name, publicId, systemID, notationName):        """called when an unparsed ENTITY declaration has been found,           name is the entity name and publicId,, systemID are the entity           public and system identifier for that entity if available,           and notationName indicate the associated NOTATION"""        pass    def warning(self, msg):        print msg    def error(self, msg):        raise parserError(msg)    def fatalError(self, msg):        raise parserError(msg)## This class is the ancestor of all the Node classes. It provides# the basic functionalities shared by all nodes (and handle# gracefylly the exception), like name, navigation in the tree,# doc reference, content access and serializing to a string or URI#class xmlCore:    def __init__(self, _obj=None):        if _obj != None:             self._o = _obj;            return        self._o = None    def __str__(self):        return self.serialize()    def get_parent(self):        ret = libxml2mod.parent(self._o)        if ret == None:            return None        return xmlNode(_obj=ret)    def get_children(self):        ret = libxml2mod.children(self._o)        if ret == None:            return None        return xmlNode(_obj=ret)    def get_last(self):        ret = libxml2mod.last(self._o)        if ret == None:            return None        return xmlNode(_obj=ret)    def get_next(self):        ret = libxml2mod.next(self._o)        if ret == None:            return None        return xmlNode(_obj=ret)    def get_properties(self):        ret = libxml2mod.properties(self._o)        if ret == None:            return None        return xmlAttr(_obj=ret)    def get_prev(self):        ret = libxml2mod.prev(self._o)        if ret == None:            return None        return xmlNode(_obj=ret)    def get_content(self):        return libxml2mod.xmlNodeGetContent(self._o)    getContent = get_content  # why is this duplicate naming needed ?    def get_name(self):        return libxml2mod.name(self._o)    def get_type(self):        return libxml2mod.type(self._o)    def get_doc(self):        ret = libxml2mod.doc(self._o)        if ret == None:            if self.type in ["document_xml", "document_html"]:                return xmlDoc(_obj=self._o)            else:                return None        return xmlDoc(_obj=ret)    #    # Those are common attributes to nearly all type of nodes    # defined as python2 properties    #     import sys    if float(sys.version[0:3]) < 2.2:        def __getattr__(self, attr):            if attr == "parent":                ret = libxml2mod.parent(self._o)                if ret == None:                    return None                return xmlNode(_obj=ret)            elif attr == "properties":                ret = libxml2mod.properties(self._o)                if ret == None:                    return None                return xmlAttr(_obj=ret)            elif attr == "children":                ret = libxml2mod.children(self._o)                if ret == None:                    return None                return xmlNode(_obj=ret)            elif attr == "last":                ret = libxml2mod.last(self._o)                if ret == None:                    return None                return xmlNode(_obj=ret)            elif attr == "next":                ret = libxml2mod.next(self._o)                if ret == None:                    return None                return xmlNode(_obj=ret)            elif attr == "prev":                ret = libxml2mod.prev(self._o)                if ret == None:                    return None                return xmlNode(_obj=ret)            elif attr == "content":                return libxml2mod.xmlNodeGetContent(self._o)            elif attr == "name":                return libxml2mod.name(self._o)            elif attr == "type":                return libxml2mod.type(self._o)            elif attr == "doc":                ret = libxml2mod.doc(self._o)                if ret == None:                    if self.type == "document_xml" or self.type == "document_html":                        return xmlDoc(_obj=self._o)                    else:                        return None                return xmlDoc(_obj=ret)            raise AttributeError,attr    else:        parent = property(get_parent, None, None, "Parent node")        children = property(get_children, None, None, "First child node")        last = property(get_last, None, None, "Last sibling node")        next = property(get_next, None, None, "Next sibling node")        prev = property(get_prev, None, None, "Previous sibling node")        properties = property(get_properties, None, None, "List of properies")

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -