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

📄 libxml.py

📁 libxml,在UNIX/LINUX下非常重要的一个库,为XML相关应用提供方便.目前上载的是最新版本,若要取得最新版本,请参考里面的readme.
💻 PY
📖 第 1 页 / 共 2 页
字号:
        content = property(get_content, None, None, "Content of this node")        name = property(get_name, None, None, "Node name")        type = property(get_type, None, None, "Node type")        doc = property(get_doc, None, None, "The document this node belongs to")    #    # Serialization routines, the optional arguments have the following    # meaning:    #     encoding: string to ask saving in a specific encoding    #     indent: if 1 the serializer is asked to indent the output    #    def serialize(self, encoding = None, format = 0):        return libxml2mod.serializeNode(self._o, encoding, format)    def saveTo(self, file, encoding = None, format = 0):        return libxml2mod.saveNodeTo(self._o, file, encoding, format)                #    # Canonicalization routines:    #    #   nodes: the node set (tuple or list) to be included in the    #     canonized image or None if all document nodes should be    #     included.    #   exclusive: the exclusive flag (0 - non-exclusive    #     canonicalization; otherwise - exclusive canonicalization)    #   prefixes: the list of inclusive namespace prefixes (strings),    #     or None if there is no inclusive namespaces (only for    #     exclusive canonicalization, ignored otherwise)    #   with_comments: include comments in the result (!=0) or not    #     (==0)    def c14nMemory(self,                   nodes=None,                   exclusive=0,                   prefixes=None,                   with_comments=0):        if nodes:            nodes = map(lambda n: n._o, nodes)        return libxml2mod.xmlC14NDocDumpMemory(            self.get_doc()._o,            nodes,            exclusive != 0,            prefixes,            with_comments != 0)    def c14nSaveTo(self,                   file,                   nodes=None,                   exclusive=0,                   prefixes=None,                   with_comments=0):        if nodes:            nodes = map(lambda n: n._o, nodes)        return libxml2mod.xmlC14NDocSaveTo(            self.get_doc()._o,            nodes,            exclusive != 0,            prefixes,            with_comments != 0,            file)    #    # Selecting nodes using XPath, a bit slow because the context    # is allocated/freed every time but convenient.    #    def xpathEval(self, expr):        doc = self.doc        if doc == None:            return None        ctxt = doc.xpathNewContext()        ctxt.setContextNode(self)        res = ctxt.xpathEval(expr)        ctxt.xpathFreeContext()        return res#    ##    # Selecting nodes using XPath, faster because the context#    # is allocated just once per xmlDoc.#    ##    # Removed: DV memleaks c.f. #126735#    ##    def xpathEval2(self, expr):#        doc = self.doc#        if doc == None:#            return None#        try:#            doc._ctxt.setContextNode(self)#        except:#            doc._ctxt = doc.xpathNewContext()#            doc._ctxt.setContextNode(self)#        res = doc._ctxt.xpathEval(expr)#        return res    def xpathEval2(self, expr):        return self.xpathEval(expr)    # support for python2 iterators    def walk_depth_first(self):        return xmlCoreDepthFirstItertor(self)    def walk_breadth_first(self):        return xmlCoreBreadthFirstItertor(self)    __iter__ = walk_depth_first    def free(self):        try:            self.doc._ctxt.xpathFreeContext()        except:            pass        libxml2mod.xmlFreeDoc(self._o)## implements the depth-first iterator for libxml2 DOM tree#class xmlCoreDepthFirstItertor:    def __init__(self, node):        self.node = node        self.parents = []    def __iter__(self):        return self    def next(self):        while 1:            if self.node:                ret = self.node                self.parents.append(self.node)                self.node = self.node.children                return ret            try:                parent = self.parents.pop()            except IndexError:                raise StopIteration            self.node = parent.next## implements the breadth-first iterator for libxml2 DOM tree#class xmlCoreBreadthFirstItertor:    def __init__(self, node):        self.node = node        self.parents = []    def __iter__(self):        return self    def next(self):        while 1:            if self.node:                ret = self.node                self.parents.append(self.node)                self.node = self.node.next                return ret            try:                parent = self.parents.pop()            except IndexError:                raise StopIteration            self.node = parent.children## converters to present a nicer view of the XPath returns#def nodeWrap(o):    # TODO try to cast to the most appropriate node class    name = libxml2mod.type(o)    if name == "element" or name == "text":        return xmlNode(_obj=o)    if name == "attribute":        return xmlAttr(_obj=o)    if name[0:8] == "document":        return xmlDoc(_obj=o)    if name == "namespace":        return xmlNs(_obj=o)    if name == "elem_decl":        return xmlElement(_obj=o)    if name == "attribute_decl":        return xmlAttribute(_obj=o)    if name == "entity_decl":        return xmlEntity(_obj=o)    if name == "dtd":        return xmlDtd(_obj=o)    return xmlNode(_obj=o)def xpathObjectRet(o):    if type(o) == type([]) or type(o) == type(()):        ret = map(lambda x: nodeWrap(x), o)        return ret    return o## register an XPath function#def registerXPathFunction(ctxt, name, ns_uri, f):    ret = libxml2mod.xmlRegisterXPathFunction(ctxt, name, ns_uri, f)## For the xmlTextReader parser configuration#PARSER_LOADDTD=1PARSER_DEFAULTATTRS=2PARSER_VALIDATE=3PARSER_SUBST_ENTITIES=4## For the error callback severities#PARSER_SEVERITY_VALIDITY_WARNING=1PARSER_SEVERITY_VALIDITY_ERROR=2PARSER_SEVERITY_WARNING=3PARSER_SEVERITY_ERROR=4## register the libxml2 error handler#def registerErrorHandler(f, ctx):    """Register a Python written function to for error reporting.       The function is called back as f(ctx, error). """    import sys    if not sys.modules.has_key('libxslt'):        # normal behaviour when libxslt is not imported        ret = libxml2mod.xmlRegisterErrorHandler(f,ctx)    else:        # when libxslt is already imported, one must        # use libxst's error handler instead        import libxslt        ret = libxslt.registerErrorHandler(f,ctx)    return retclass parserCtxtCore:    def __init__(self, _obj=None):        if _obj != None:             self._o = _obj;            return        self._o = None    def __del__(self):        if self._o != None:            libxml2mod.xmlFreeParserCtxt(self._o)        self._o = None    def setErrorHandler(self,f,arg):        """Register an error handler that will be called back as           f(arg,msg,severity,reserved).                      @reserved is currently always None."""        libxml2mod.xmlParserCtxtSetErrorHandler(self._o,f,arg)    def getErrorHandler(self):        """Return (f,arg) as previously registered with setErrorHandler           or (None,None)."""        return libxml2mod.xmlParserCtxtGetErrorHandler(self._o)    def addLocalCatalog(self, uri):        """Register a local catalog with the parser"""        return libxml2mod.addLocalCatalog(self._o, uri)    class ValidCtxtCore:    def __init__(self, *args, **kw):        pass    def setValidityErrorHandler(self, err_func, warn_func, arg=None):        """        Register error and warning handlers for DTD validation.        These will be called back as f(msg,arg)        """        libxml2mod.xmlSetValidErrors(self._o, err_func, warn_func, arg)    class SchemaValidCtxtCore:    def __init__(self, *args, **kw):        pass    def setValidityErrorHandler(self, err_func, warn_func, arg=None):        """        Register error and warning handlers for Schema validation.        These will be called back as f(msg,arg)        """        libxml2mod.xmlSchemaSetValidErrors(self._o, err_func, warn_func, arg)class relaxNgValidCtxtCore:    def __init__(self, *args, **kw):        pass    def setValidityErrorHandler(self, err_func, warn_func, arg=None):        """        Register error and warning handlers for RelaxNG validation.        These will be called back as f(msg,arg)        """        libxml2mod.xmlRelaxNGSetValidErrors(self._o, err_func, warn_func, arg)    def _xmlTextReaderErrorFunc((f,arg),msg,severity,locator):    """Intermediate callback to wrap the locator"""    return f(arg,msg,severity,xmlTextReaderLocator(locator))class xmlTextReaderCore:    def __init__(self, _obj=None):        self.input = None        if _obj != None:self._o = _obj;return        self._o = None    def __del__(self):        if self._o != None:            libxml2mod.xmlFreeTextReader(self._o)        self._o = None    def SetErrorHandler(self,f,arg):        """Register an error handler that will be called back as           f(arg,msg,severity,locator)."""        if f is None:            libxml2mod.xmlTextReaderSetErrorHandler(\                self._o,None,None)        else:            libxml2mod.xmlTextReaderSetErrorHandler(\                self._o,_xmlTextReaderErrorFunc,(f,arg))    def GetErrorHandler(self):        """Return (f,arg) as previously registered with setErrorHandler           or (None,None)."""        f,arg = libxml2mod.xmlTextReaderGetErrorHandler(self._o)        if f is None:            return None,None        else:            # assert f is _xmlTextReaderErrorFunc            return arg## The cleanup now goes though a wrappe in libxml.c#def cleanupParser():    libxml2mod.xmlPythonCleanupParser()# WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING## Everything before this line comes from libxml.py # Everything after this line is automatically generated## WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING

⌨️ 快捷键说明

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