__pycache__/NodeFilter.cpython-36.opt-1.pyc000064400000001671147204745200014406 0ustar003 \@sGdddZdS)c@sXeZdZdZdZdZdZdZdZdZ dZ dZ dZ d Z d Zd Zd Zd ZdZdZddZdS) NodeFilterzL This is the DOM2 NodeFilter interface. It contains only constants. l @iiicCstdS)N)NotImplementedError)selfZnoder*/usr/lib64/python3.6/xml/dom/NodeFilter.py acceptNodeszNodeFilter.acceptNodeN)__name__ __module__ __qualname____doc__Z FILTER_ACCEPTZ FILTER_REJECTZ FILTER_SKIPZSHOW_ALLZ SHOW_ELEMENTZSHOW_ATTRIBUTEZ SHOW_TEXTZSHOW_CDATA_SECTIONZSHOW_ENTITY_REFERENCEZ SHOW_ENTITYZSHOW_PROCESSING_INSTRUCTIONZ SHOW_COMMENTZ SHOW_DOCUMENTZSHOW_DOCUMENT_TYPEZSHOW_DOCUMENT_FRAGMENTZ SHOW_NOTATIONrrrrrrs$rN)rrrrrs__pycache__/NodeFilter.cpython-36.opt-2.pyc000064400000001534147204745200014405 0ustar003 \@sGdddZdS)c@sTeZdZdZdZdZdZdZdZdZ dZ dZ dZ d Z d Zd Zd Zd ZdZddZdS) NodeFilterl @iiicCstdS)N)NotImplementedError)selfZnoder*/usr/lib64/python3.6/xml/dom/NodeFilter.py acceptNodeszNodeFilter.acceptNodeN)__name__ __module__ __qualname__Z FILTER_ACCEPTZ FILTER_REJECTZ FILTER_SKIPZSHOW_ALLZ SHOW_ELEMENTZSHOW_ATTRIBUTEZ SHOW_TEXTZSHOW_CDATA_SECTIONZSHOW_ENTITY_REFERENCEZ SHOW_ENTITYZSHOW_PROCESSING_INSTRUCTIONZ SHOW_COMMENTZ SHOW_DOCUMENTZSHOW_DOCUMENT_TYPEZSHOW_DOCUMENT_FRAGMENTZ SHOW_NOTATIONrrrrrrs"rN)rrrrrs__pycache__/NodeFilter.cpython-36.pyc000064400000001671147204745200013447 0ustar003 \@sGdddZdS)c@sXeZdZdZdZdZdZdZdZdZ dZ dZ dZ d Z d Zd Zd Zd ZdZdZddZdS) NodeFilterzL This is the DOM2 NodeFilter interface. It contains only constants. l @iiicCstdS)N)NotImplementedError)selfZnoder*/usr/lib64/python3.6/xml/dom/NodeFilter.py acceptNodeszNodeFilter.acceptNodeN)__name__ __module__ __qualname____doc__Z FILTER_ACCEPTZ FILTER_REJECTZ FILTER_SKIPZSHOW_ALLZ SHOW_ELEMENTZSHOW_ATTRIBUTEZ SHOW_TEXTZSHOW_CDATA_SECTIONZSHOW_ENTITY_REFERENCEZ SHOW_ENTITYZSHOW_PROCESSING_INSTRUCTIONZ SHOW_COMMENTZ SHOW_DOCUMENTZSHOW_DOCUMENT_TYPEZSHOW_DOCUMENT_FRAGMENTZ SHOW_NOTATIONrrrrrrs$rN)rrrrrs__pycache__/__init__.cpython-36.opt-1.pyc000064400000012471147204745200014112 0ustar003 \@sdZGdddZdZdZdZdZdZdZd Zd Z d Z d Z d Z dZ dZdZdZdZGdddeZGdddeZGdddeZGdddeZGdddeZGdddeZGdd d eZGd!d"d"eZGd#d$d$eZGd%d&d&eZGd'd(d(eZGd)d*d*eZGd+d,d,eZGd-d.d.eZ Gd/d0d0eZ!Gd1d2d2eZ"Gd3d4d4eZ#Gd5d6d6Z$d7Z%d8Z&d9Z'd:Z(d:Z)dd;l*m+Z+m,Z,d:S)src@seZdZeZdS) IndexSizeErrN)rrrINDEX_SIZE_ERRr!rrrrr#Lsr#c@seZdZeZdS)DomstringSizeErrN)rrrDOMSTRING_SIZE_ERRr!rrrrr%Osr%c@seZdZeZdS)HierarchyRequestErrN)rrrHIERARCHY_REQUEST_ERRr!rrrrr'Rsr'c@seZdZeZdS)WrongDocumentErrN)rrrWRONG_DOCUMENT_ERRr!rrrrr)Usr)c@seZdZeZdS)InvalidCharacterErrN)rrrINVALID_CHARACTER_ERRr!rrrrr+Xsr+c@seZdZeZdS)NoDataAllowedErrN)rrrNO_DATA_ALLOWED_ERRr!rrrrr-[sr-c@seZdZeZdS)NoModificationAllowedErrN)rrrNO_MODIFICATION_ALLOWED_ERRr!rrrrr/^sr/c@seZdZeZdS) NotFoundErrN)rrr NOT_FOUND_ERRr!rrrrr1asr1c@seZdZeZdS)NotSupportedErrN)rrrNOT_SUPPORTED_ERRr!rrrrr3dsr3c@seZdZeZdS)InuseAttributeErrN)rrrINUSE_ATTRIBUTE_ERRr!rrrrr5gsr5c@seZdZeZdS)InvalidStateErrN)rrrINVALID_STATE_ERRr!rrrrr7jsr7c@seZdZeZdS) SyntaxErrN)rrr SYNTAX_ERRr!rrrrr9msr9c@seZdZeZdS)InvalidModificationErrN)rrrINVALID_MODIFICATION_ERRr!rrrrr;psr;c@seZdZeZdS) NamespaceErrN)rrr NAMESPACE_ERRr!rrrrr=ssr=c@seZdZeZdS)InvalidAccessErrN)rrrINVALID_ACCESS_ERRr!rrrrr?vsr?c@seZdZeZdS) ValidationErrN)rrrVALIDATION_ERRr!rrrrrAysrAc@s eZdZdZdZdZdZdZdS)UserDataHandlerzBClass giving the operation constants for UserDataHandler.handle().rrrrN)rrrrZ NODE_CLONEDZ NODE_IMPORTEDZ NODE_DELETEDZ NODE_RENAMEDrrrrrC|s rCz$http://www.w3.org/XML/1998/namespacezhttp://www.w3.org/2000/xmlns/zhttp://www.w3.org/1999/xhtmlN)getDOMImplementationregisterDOMImplementation)-rrr$r&r(r*r,r.r0r2r4r6r8r:r<r>r@rBrrr#r%r'r)r+r-r/r1r3r5r7r9r;r=r?rArCZ XML_NAMESPACEZXMLNS_NAMESPACEZXHTML_NAMESPACEZEMPTY_NAMESPACEZ EMPTY_PREFIXZdomregrDrErrrrsR __pycache__/__init__.cpython-36.opt-2.pyc000064400000011036147204745200014107 0ustar003 \@sGdddZdZdZdZdZdZdZdZd Zd Z d Z d Z d Z dZ dZdZdZGdddeZGdddeZGdddeZGdddeZGdddeZGdddeZGdddeZGd d!d!eZGd"d#d#eZGd$d%d%eZGd&d'd'eZGd(d)d)eZGd*d+d+eZGd,d-d-eZGd.d/d/eZ Gd0d1d1eZ!Gd2d3d3eZ"Gd4d5d5Z#d6Z$d7Z%d8Z&d9Z'd9Z(dd:l)m*Z*m+Z+d9S);c@s@eZdZfZdZdZdZdZdZdZ dZ dZ d Z d Z d Zd Zd S)Node N)__name__ __module__ __qualname__ __slots__Z ELEMENT_NODEZATTRIBUTE_NODEZ TEXT_NODEZCDATA_SECTION_NODEZENTITY_REFERENCE_NODEZ ENTITY_NODEZPROCESSING_INSTRUCTION_NODEZ COMMENT_NODEZ DOCUMENT_NODEZDOCUMENT_TYPE_NODEZDOCUMENT_FRAGMENT_NODEZ NOTATION_NODErr(/usr/lib64/python3.6/xml/dom/__init__.pyrs rrrrrrrrr r r r r c@seZdZddZddZdS) DOMExceptioncOs(|jtkrtdtj|f||dS)Nz0DOMException should not be instantiated directly) __class__r RuntimeError Exception__init__)selfargskwrrrrBs zDOMException.__init__cCs|jS)N)code)rrrr _get_codeHszDOMException._get_codeN)rrrrr!rrrrr>src@seZdZeZdS) IndexSizeErrN)rrrINDEX_SIZE_ERRr rrrrr"Lsr"c@seZdZeZdS)DomstringSizeErrN)rrrDOMSTRING_SIZE_ERRr rrrrr$Osr$c@seZdZeZdS)HierarchyRequestErrN)rrrHIERARCHY_REQUEST_ERRr rrrrr&Rsr&c@seZdZeZdS)WrongDocumentErrN)rrrWRONG_DOCUMENT_ERRr rrrrr(Usr(c@seZdZeZdS)InvalidCharacterErrN)rrrINVALID_CHARACTER_ERRr rrrrr*Xsr*c@seZdZeZdS)NoDataAllowedErrN)rrrNO_DATA_ALLOWED_ERRr rrrrr,[sr,c@seZdZeZdS)NoModificationAllowedErrN)rrrNO_MODIFICATION_ALLOWED_ERRr rrrrr.^sr.c@seZdZeZdS) NotFoundErrN)rrr NOT_FOUND_ERRr rrrrr0asr0c@seZdZeZdS)NotSupportedErrN)rrrNOT_SUPPORTED_ERRr rrrrr2dsr2c@seZdZeZdS)InuseAttributeErrN)rrrINUSE_ATTRIBUTE_ERRr rrrrr4gsr4c@seZdZeZdS)InvalidStateErrN)rrrINVALID_STATE_ERRr rrrrr6jsr6c@seZdZeZdS) SyntaxErrN)rrr SYNTAX_ERRr rrrrr8msr8c@seZdZeZdS)InvalidModificationErrN)rrrINVALID_MODIFICATION_ERRr rrrrr:psr:c@seZdZeZdS) NamespaceErrN)rrr NAMESPACE_ERRr rrrrr<ssr<c@seZdZeZdS)InvalidAccessErrN)rrrINVALID_ACCESS_ERRr rrrrr>vsr>c@seZdZeZdS) ValidationErrN)rrrVALIDATION_ERRr rrrrr@ysr@c@seZdZdZdZdZdZdS)UserDataHandlerrrrrN)rrrZ NODE_CLONEDZ NODE_IMPORTEDZ NODE_DELETEDZ NODE_RENAMEDrrrrrB|srBz$http://www.w3.org/XML/1998/namespacezhttp://www.w3.org/2000/xmlns/zhttp://www.w3.org/1999/xhtmlN)getDOMImplementationregisterDOMImplementation),rr#r%r'r)r+r-r/r1r3r5r7r9r;r=r?rArrr"r$r&r(r*r,r.r0r2r4r6r8r:r<r>r@rBZ XML_NAMESPACEZXMLNS_NAMESPACEZXHTML_NAMESPACEZEMPTY_NAMESPACEZ EMPTY_PREFIXZdomregrCrDrrrrsP __pycache__/__init__.cpython-36.pyc000064400000012471147204745200013153 0ustar003 \@sdZGdddZdZdZdZdZdZdZd Zd Z d Z d Z d Z dZ dZdZdZdZGdddeZGdddeZGdddeZGdddeZGdddeZGdddeZGdd d eZGd!d"d"eZGd#d$d$eZGd%d&d&eZGd'd(d(eZGd)d*d*eZGd+d,d,eZGd-d.d.eZ Gd/d0d0eZ!Gd1d2d2eZ"Gd3d4d4eZ#Gd5d6d6Z$d7Z%d8Z&d9Z'd:Z(d:Z)dd;l*m+Z+m,Z,d:S)src@seZdZeZdS) IndexSizeErrN)rrrINDEX_SIZE_ERRr!rrrrr#Lsr#c@seZdZeZdS)DomstringSizeErrN)rrrDOMSTRING_SIZE_ERRr!rrrrr%Osr%c@seZdZeZdS)HierarchyRequestErrN)rrrHIERARCHY_REQUEST_ERRr!rrrrr'Rsr'c@seZdZeZdS)WrongDocumentErrN)rrrWRONG_DOCUMENT_ERRr!rrrrr)Usr)c@seZdZeZdS)InvalidCharacterErrN)rrrINVALID_CHARACTER_ERRr!rrrrr+Xsr+c@seZdZeZdS)NoDataAllowedErrN)rrrNO_DATA_ALLOWED_ERRr!rrrrr-[sr-c@seZdZeZdS)NoModificationAllowedErrN)rrrNO_MODIFICATION_ALLOWED_ERRr!rrrrr/^sr/c@seZdZeZdS) NotFoundErrN)rrr NOT_FOUND_ERRr!rrrrr1asr1c@seZdZeZdS)NotSupportedErrN)rrrNOT_SUPPORTED_ERRr!rrrrr3dsr3c@seZdZeZdS)InuseAttributeErrN)rrrINUSE_ATTRIBUTE_ERRr!rrrrr5gsr5c@seZdZeZdS)InvalidStateErrN)rrrINVALID_STATE_ERRr!rrrrr7jsr7c@seZdZeZdS) SyntaxErrN)rrr SYNTAX_ERRr!rrrrr9msr9c@seZdZeZdS)InvalidModificationErrN)rrrINVALID_MODIFICATION_ERRr!rrrrr;psr;c@seZdZeZdS) NamespaceErrN)rrr NAMESPACE_ERRr!rrrrr=ssr=c@seZdZeZdS)InvalidAccessErrN)rrrINVALID_ACCESS_ERRr!rrrrr?vsr?c@seZdZeZdS) ValidationErrN)rrrVALIDATION_ERRr!rrrrrAysrAc@s eZdZdZdZdZdZdZdS)UserDataHandlerzBClass giving the operation constants for UserDataHandler.handle().rrrrN)rrrrZ NODE_CLONEDZ NODE_IMPORTEDZ NODE_DELETEDZ NODE_RENAMEDrrrrrC|s rCz$http://www.w3.org/XML/1998/namespacezhttp://www.w3.org/2000/xmlns/zhttp://www.w3.org/1999/xhtmlN)getDOMImplementationregisterDOMImplementation)-rrr$r&r(r*r,r.r0r2r4r6r8r:r<r>r@rBrrr#r%r'r)r+r-r/r1r3r5r7r9r;r=r?rArCZ XML_NAMESPACEZXMLNS_NAMESPACEZXHTML_NAMESPACEZEMPTY_NAMESPACEZ EMPTY_PREFIXZdomregrDrErrrrsR __pycache__/domreg.cpython-36.opt-1.pyc000064400000005407147204745200013631 0ustar003 \{ @sDdZddlZdddZiZddZdd Zdffd d Zd d ZdS)zRegistration facilities for DOM. This module should not be used directly. Instead, the functions getDOMImplementation and registerDOMImplementation should be imported from xml.dom.Nzxml.dom.minidomzxml.dom.DOMImplementation)ZminidomZ4DOMcCs |t|<dS)aIregisterDOMImplementation(name, factory) Register the factory function with the name. The factory function should return an object which implements the DOMImplementation interface. The factory function can either return the same object, or a new one (e.g. if that implementation supports some customization).N) registered)namefactoryr&/usr/lib64/python3.6/xml/dom/domreg.pyregisterDOMImplementations rcCs&x |D]\}}|j||sdSqWdS)zF_good_enough(dom, features) -> Return 1 if the dom offers the featuresr)Z hasFeature)domfeaturesfvrrr _good_enough s r c Csddl}d}tj|}|r2t|iidg}|jS|r@t|Stjj rdd|j krdt|j ddSt |t rvt |}x$tj D]}|}t||r|SqWxDtjD]8}yt|d}Wntk rwYnXt||r|SqWtddS)aSgetDOMImplementation(name = None, features = ()) -> DOM implementation. Return a suitable DOM implementation. The name is either well-known, the module name of a DOM implementation, or None. If it is not None, imports the corresponding module and returns DOMImplementation object if the import succeeds. If name is not given, consider the available implementations to find one with the required feature set. If no implementation can be found, raise an ImportError. The features list must be a sequence of (feature, version) pairs which are passed to hasFeature.rNgetDOMImplementationZ PYTHON_DOM)rz$no suitable DOM implementation found)oswell_known_implementationsget __import__rrsysflagsignore_environmentenviron isinstancestr_parse_feature_stringvaluesr keys Exception ImportError)rr rZcreatormodr rrrr's0      rcCsg}|j}d}t|}xp||kr||}|ddkrDtd|f|d}d}||krx||}|ddkrx|d}|}|j||fqWt|S)Nr 0123456789zbad feature name: %rr)splitlen ValueErrorappendtuple)sr partsiZlengthZfeatureversionr rrrrRs"   r)__doc__rrrrr rrrrrrs +__pycache__/domreg.cpython-36.opt-2.pyc000064400000003125147204745200013625 0ustar003 \{ @s@ddlZdddZiZddZddZdffd d Zd d ZdS) Nzxml.dom.minidomzxml.dom.DOMImplementation)ZminidomZ4DOMcCs |t|<dS)N) registered)namefactoryr&/usr/lib64/python3.6/xml/dom/domreg.pyregisterDOMImplementations rcCs&x |D]\}}|j||sdSqWdS)Nr)Z hasFeature)domfeaturesfvrrr _good_enough s r c Csddl}d}tj|}|r2t|iidg}|jS|r@t|Stjj rdd|j krdt|j ddSt |t rvt |}x$tj D]}|}t||r|SqWxDtjD]8}yt|d}Wntk rwYnXt||r|SqWtddS)NrgetDOMImplementationZ PYTHON_DOM)rz$no suitable DOM implementation found)oswell_known_implementationsget __import__rrsysflagsignore_environmentenviron isinstancestr_parse_feature_stringvaluesr keys Exception ImportError)rr rZcreatormodr rrrr's0      rcCsg}|j}d}t|}xp||kr||}|ddkrDtd|f|d}d}||krx||}|ddkrx|d}|}|j||fqWt|S)Nr 0123456789zbad feature name: %rr)splitlen ValueErrorappendtuple)sr partsiZlengthZfeatureversionr rrrrRs"   r)rrrrr rrrrrr s +__pycache__/domreg.cpython-36.pyc000064400000005407147204745200012672 0ustar003 \{ @sDdZddlZdddZiZddZdd Zdffd d Zd d ZdS)zRegistration facilities for DOM. This module should not be used directly. Instead, the functions getDOMImplementation and registerDOMImplementation should be imported from xml.dom.Nzxml.dom.minidomzxml.dom.DOMImplementation)ZminidomZ4DOMcCs |t|<dS)aIregisterDOMImplementation(name, factory) Register the factory function with the name. The factory function should return an object which implements the DOMImplementation interface. The factory function can either return the same object, or a new one (e.g. if that implementation supports some customization).N) registered)namefactoryr&/usr/lib64/python3.6/xml/dom/domreg.pyregisterDOMImplementations rcCs&x |D]\}}|j||sdSqWdS)zF_good_enough(dom, features) -> Return 1 if the dom offers the featuresr)Z hasFeature)domfeaturesfvrrr _good_enough s r c Csddl}d}tj|}|r2t|iidg}|jS|r@t|Stjj rdd|j krdt|j ddSt |t rvt |}x$tj D]}|}t||r|SqWxDtjD]8}yt|d}Wntk rwYnXt||r|SqWtddS)aSgetDOMImplementation(name = None, features = ()) -> DOM implementation. Return a suitable DOM implementation. The name is either well-known, the module name of a DOM implementation, or None. If it is not None, imports the corresponding module and returns DOMImplementation object if the import succeeds. If name is not given, consider the available implementations to find one with the required feature set. If no implementation can be found, raise an ImportError. The features list must be a sequence of (feature, version) pairs which are passed to hasFeature.rNgetDOMImplementationZ PYTHON_DOM)rz$no suitable DOM implementation found)oswell_known_implementationsget __import__rrsysflagsignore_environmentenviron isinstancestr_parse_feature_stringvaluesr keys Exception ImportError)rr rZcreatormodr rrrr's0      rcCsg}|j}d}t|}xp||kr||}|ddkrDtd|f|d}d}||krx||}|ddkrx|d}|}|j||fqWt|S)Nr 0123456789zbad feature name: %rr)splitlen ValueErrorappendtuple)sr partsiZlengthZfeatureversionr rrrrRs"   r)__doc__rrrrr rrrrrrs +__pycache__/expatbuilder.cpython-36.opt-1.pyc000064400000063774147204745200015057 0ustar003 \ @sdZddlmZmZmZddlmZmZmZddlm Z ddl m Z m Z ddl mZejZejZejZejjZejjZejjZejjZejZejddejdd ejdd ejdd ejdd ejdd ejddejddejddd ZGdddeZddZddZGdddZeeefZ GdddeZ!GdddeZ"Gddde"Z#Gd d!d!e"Z$d"Z%d#e%Z&Gd$d%d%eZ'Gd&d'd'Z(Gd(d)d)e(eZ)Gd*d+d+e(e'Z*Gd,d-d-e+Z,Gd.d/d/eZ-d;d1d2Z.dd7d8Z1d9d:Z2dS)?zFacility to use the Expat parser to load a minidom instance from a string or file. This avoids all the overhead of SAX and pulldom to gain performance. ) xmlbuilderminidomNode)EMPTY_NAMESPACE EMPTY_PREFIXXMLNS_NAMESPACE)expat) _append_child_set_attribute_node) NodeFilterNZcdata enumerationentityentitiesidZidrefZidrefsZnmtokenZnmtokens) ZCDATAENUMZENTITYZENTITIESIDZIDREFZIDREFSZNMTOKENZNMTOKENSc@sZeZdZdZdddZddZd d Zd d Zd dZddZ ddZ ddZ ddZ dS) ElementInfo _attr_info_modeltagNameNcCs||_g|_||_dS)N)rrr)selfrmodelr,/usr/lib64/python3.6/xml/dom/expatbuilder.py__init__?szElementInfo.__init__cCs|j|j|jfS)N)rrr)rrrr __getstate__DszElementInfo.__getstate__cCs|\|_|_|_dS)N)rrr)rstaterrr __setstate__GszElementInfo.__setstate__cCsJxB|jD]8}|d|kr|d}|ddkr4tdSt|dSqWtjS)Nr(rr!)r _typeinfo_mapr_no_type)ranameinfotrrrgetAttributeTypeJs   zElementInfo.getAttributeTypecCstjS)N)rr#)rZ namespaceURIZ localNamerrrgetAttributeTypeNSTszElementInfo.getAttributeTypeNScCs,|jr$|jd}|tjjtjjfkSdSdS)NrF)rrrZ XML_CTYPE_ANYZXML_CTYPE_MIXED)rtyperrrisElementContentWs   zElementInfo.isElementContentcCs |jr|jdtjjkSdSdS)NrF)rrrZXML_CTYPE_EMPTY)rrrrisEmpty_szElementInfo.isEmptycCs,x&|jD]}|d|kr|ddkSqWdS)NrrrFr!)r)rr$r%rrrisIdes  zElementInfo.isIdcCs|j||fS)N)r,)rZeuriZenameZaurir$rrrisIdNSkszElementInfo.isIdNS)rrr)N) __name__ __module__ __qualname__ __slots__rrrr'r(r*r+r,r-rrrrr<s  rcCs |j||S)N)_intern_setdefault)buildersrrr_internosr5cCs|jd}|j}t|dkrR|\}}}|||}d||f}|||}|||}n4t|dkrz|\}}t}|||}}n td|||||||fS)N z%s:%srz4Unsupported syntax: spaces in URIs not supported: %r)splitr2lenr ValueError)r3namepartsinternuri localnameprefixqnamerrr_parse_ns_namers         rBc@seZdZdZd;ddZddZddZd d Zd d Zd dZ ddZ ddZ ddZ ddZ ddZddZddZddZdd Zd!d"Zd#d$Zd%d&Zd'd(Zd)d*Zd+d,Zd-d.Zd/d0Zd1d2Zd3d4Zd5d6Zd7d8Zd9d:ZdS)< ExpatBuilderzPDocument builder that uses Expat to build a ParsedXML.DOM document instance.NcCsP|dkrtj}||_|jjdk r2t|jj|_n d|_t|_d|_|j dS)N) rZOptions_optionsfilterFilterVisibilityController_filterr_finish_start_element_parserreset)roptionsrrrrs zExpatBuilder.__init__cCstjS)zCreate a new parser object.)r ParserCreate)rrrr createParserszExpatBuilder.createParsercCsF|js@|j|_|jjj|_d|j_d|j_d|j_|j|j|jS)z7Return the parser object, creating a new one if needed.T) rIrMr= setdefaultr2Z buffer_textZordered_attributesZspecified_attributesinstall)rrrr getParsers   zExpatBuilder.getParsercCs,tjtdd|_|j|_|jj|_d|_dS)z6Free all data structures used during DOM construction.NF)theDOMImplementationZcreateDocumentrdocumentcurNode _elem_info_cdata)rrrrrJs   zExpatBuilder.resetcCs|j|_|j|_|j|_|j|_|jj r0|j |_ |j |_ |jjrH|j|_|jjrj|j|_|j|_|j|_n|j|_|j|_|j|_|j|_|j|_ dS)z>Install the callbacks needed to build the DOM into the parser.N)!start_doctype_decl_handlerStartDoctypeDeclHandlerfirst_element_handlerStartElementHandlerend_element_handlerEndElementHandler pi_handlerProcessingInstructionHandlerrDrentity_decl_handlerEntityDeclHandlernotation_decl_handlerNotationDeclHandlercommentscomment_handlerCommentHandlerZcdata_sectionsstart_cdata_section_handlerStartCdataSectionHandlerend_cdata_section_handlerEndCdataSectionHandlercharacter_data_handler_cdataCharacterDataHandlercharacter_data_handlerexternal_entity_ref_handlerExternalEntityRefHandlerxml_decl_handlerZXmlDeclHandlerelement_decl_handlerZElementDeclHandlerattlist_decl_handlerZAttlistDeclHandler)rparserrrrrOs$ zExpatBuilder.installc Cs|j}d}yLx:|jd}|s P|j|d|rB|jjrB|j|d}qW|jddWntk rlYnX|j}|jd|_|S) zIParse a document from a file object, returning the document node.TirFNi@) rPreadParserRdocumentElement _setup_subset ParseEscaperJrI)rfilerqZ first_bufferbufferdocrrr parseFiles$    zExpatBuilder.parseFilec CsP|j}y|j|d|j|Wntk r6YnX|j}|jd|_|S)z|jj|}t|j||jr:|jj|tkr:|jj|dS)N)rRZ createCommentr rSrGrrr)rrrrrrrcIs  zExpatBuilder.comment_handlercCsd|_d|_dS)NTF)rUr)rrrrreOsz(ExpatBuilder.start_cdata_section_handlercCsd|_d|_dS)NF)rUr)rrrrrgSsz&ExpatBuilder.end_cdata_section_handlercCsdS)Nrr)rcontextrrrrrrrlWsz(ExpatBuilder.external_entity_ref_handlercCs4|jdkr|j rt|_|j|j_|j||dS)N)rGrTrrstart_element_handlerrPrY)rr; attributesrrrrXZs z"ExpatBuilder.first_element_handlercCs|jj|}t|j|||_|rtxPtdt|dD]<}tj||tdt }||d}||_ |j|_ t ||q4W||jj k r|j|dS)Nrrr)rRZ createElementr rSranger9rAttrrrrrr rvrH)rr;rriarrrrr`s     z"ExpatBuilder.start_element_handlercCsj|jrf||jjkrdS|jj|}|tkr4t|n|tkrFt|ndS|j|_ |jj ||j dS)N) rGrRrvstartContainerrRejecter FILTER_SKIPSkipper parentNoderSrunlink)rrZfiltrrrrHqs     z"ExpatBuilder._finish_start_elementcCs|j}|j|_|j|dS)N)rSrr)rr;rSrrrrZsz ExpatBuilder.end_element_handlercCs\|jj|j}|r|j|||jrX||jjkr4dS|jj|tkrX|j j ||j dS)N) rTgetr_handle_white_text_nodesrGrRrvrrrSrr)rrSr%rrrrs   z ExpatBuilder._finish_end_elementcCsf|jjs|j rdSg}x.|jD]$}|jtkr"|jj r"|j|q"Wx|D]}|j |qPWdS)N) rDZwhitespace_in_element_contentr*rrrrstriprr)rrr%Lrrrrrs   z%ExpatBuilder._handle_white_text_nodescCs0|jj|}|dkr&t|||j|<n||_dS)N)rTrrr)rr;rr%rrrros z!ExpatBuilder.element_decl_handlerc CsF|jj|}|dkr&t|}||j|<|jjd|dd|d||gdS)Nr)rTrrrr)relemr;r)defaultZrequiredr%rrrrps   z!ExpatBuilder.attlist_decl_handlercCs2||j_||j_|dkr.|r&d|j_nd|j_dS)NrTF)rRversionencoding standalone)rrrrrrrrns  zExpatBuilder.xml_decl_handler)N) r.r/r0__doc__rrMrPrJrOr|r~rwrVrr\rirkr^r`rcrergrlrXrrHrZrrrorprnrrrrrCs:     rCc@seZdZdZd ZddZddZddZej e j ej e j eje jeje jeje jeje jeje jeje jeje jeje jeje jej e j!i Z"d S) rFzoWrapper around a DOMBuilderFilter which implements the checks to make the whatToShow filter attribute work.rEcCs ||_dS)N)rE)rrErrrrsz#FilterVisibilityController.__init__cCsT|j|j}|jj|@rL|jj|}|tkr0t|tkrHtdt ||St SdS)Nz)startContainer() returned illegal value: ) _nodetype_maskrrE whatToShowrFILTER_INTERRUPTrx_ALLOWED_FILTER_RETURNSr:reprr)rrmaskvalrrrrs   z)FilterVisibilityController.startContainercCs|j|j}|jj|@r|jj|}|tkr0t|tkrd|j}x |j ddD]}|j |qNWt S|t kr|t dt||StSdS)Nz%acceptNode() returned illegal value: )rrrErrrrxrrrZ appendChildrrr:rr)rrrrparentrrrrrs   z%FilterVisibilityController.acceptNodeN)rE)#r.r/r0rr1rrrrZ ELEMENT_NODEr Z SHOW_ELEMENTZATTRIBUTE_NODEZSHOW_ATTRIBUTErZ SHOW_TEXTrZSHOW_CDATA_SECTIONZENTITY_REFERENCE_NODEZSHOW_ENTITY_REFERENCEZ ENTITY_NODEZ SHOW_ENTITYZPROCESSING_INSTRUCTION_NODEZSHOW_PROCESSING_INSTRUCTIONZ COMMENT_NODEZ SHOW_COMMENT DOCUMENT_NODEZ SHOW_DOCUMENTZDOCUMENT_TYPE_NODEZSHOW_DOCUMENT_TYPEZDOCUMENT_FRAGMENT_NODEZSHOW_DOCUMENT_FRAGMENTZ NOTATION_NODEZ SHOW_NOTATIONrrrrrrFs" rFc@seZdZdZddZdS) FilterCrutch_builder_level _old_start_old_endcCs6d|_||_|j}|j|_|j|_|j|_|j|_dS)Nr) rrrIrYrr[rrrZ)rr3rqrrrrszFilterCrutch.__init__N)rrrr)r.r/r0r1rrrrrrsrc@s(eZdZfZddZddZddZdS)rcCs0tj|||j}xdD]}t||dqWdS)Nr]rdrjrfrhrm)r]rdrjrfrhrm)rrrIsetattr)rr3rqr;rrrrs zRejecter.__init__cGs|jd|_dS)Nr)r)rargsrrrrszRejecter.start_element_handlercGs@|jdkr0|jj}|jj||j|_|j|_n |jd|_dS)Nrr)rrrIrOrrYrr[)rrrqrrrrZ s    zRejecter.end_element_handlerN)r.r/r0r1rrrZrrrrrs rc@s eZdZfZddZddZdS)rcGs.|jj}|j||jj|k r*|jd|_dS)Nr)rrSrr)rrrrrrr-s  zSkipper.start_element_handlercGsD|jdkr*|j|jj_|j|jj_d|_n|jd|_|j|dS)Nrr)rrrrIrYrr[)rrrrrrZ3s     zSkipper.end_element_handlerN)r.r/r0r1rrZrrrrr*srz8http://xml.python.org/entities/fragment-builder/internalz %%s ]> &fragment-builder-internal;c@sJeZdZdZdddZddZddZd d Zd d Zd dZ ddZ dS)FragmentBuilderzBuilder which constructs document fragments given XML source text and a context node. The context node is expected to provide information about the namespace declarations which are in scope at the start of the fragment. NcCs6|jtkr||_||_n|j|_||_tj||dS)N)rroriginalDocumentrrrCr)rrrKrrrr[s  zFragmentBuilder.__init__cCstj|d|_dS)N)rCrJfragment)rrrrrJds zFragmentBuilder.resetcCs|j|jS)zRParse a document fragment from a file object, returning the fragment node.)r~rt)rryrrrr|hszFragmentBuilder.parseFilec Cs||_|j}|jj}d}|rV|jp*|j}|jrDd|j|jf}qZ|jrZd|j}nd}|j}t |||f}y|j |dWn|j YnX|j }|j |S)zMParse a document fragment from a string, returning the fragment node.rszPUBLIC "%s" "%s"z SYSTEM "%s"r) _sourcerPrrr_getDeclarationsrr _getNSattrs_FRAGMENT_BUILDER_TEMPLATErurJr) rr}rqrZidentrZnsattrsrRrrrrr~ms, zFragmentBuilder.parseStringcCs|jjj}d}|rxbt|jjD]R}|jj|}|r>|d}d||jf}|jrfd||j|j f}q"d||j f}q"Wxt|j jD]}|j j|}|r|d}d||jf}|jrd||j|j f}n&|j rd||j f}nd ||j j f}|j rd ||j f}|d }qW|S) zRe-create the internal subset from the DocumentType node. This is only needed if we don't already have the internalSubset as a string. rsz z%sz%s SYSTEM "%s">z %s)rrrrrZlengthitemZnodeNamerrrZ firstChildrr)rrr4rZnotationr rrrrs6    z FragmentBuilder._getDeclarationscCsdS)Nrsr)rrrrrszFragmentBuilder._getNSattrsc Cs~|tkrh|j}|j}|jj|}|j|_|jj|_|j|_z|j|j dWd||_||_d|_ XdSt j |||||SdS)Nrr) $_FRAGMENT_BUILDER_INTERNAL_SYSTEM_IDrRrSrIZExternalEntityParserCreaterZcreateDocumentFragmentrrurrCrl)rrrrrZ old_documentZ old_cur_noderqrrrrls  z+FragmentBuilder.external_entity_ref_handler)N) r.r/r0rrrJr|r~rrrlrrrrrRs $rc@s8eZdZdZddZddZddZdd Zd d Zd S) Namespacesz7Mix-in class for builders; adds support for namespaces.cCs g|_dS)N)_ns_ordered_prefixes)rrrr_initNamespacesszNamespaces._initNamespacescCstjdd}d|_|S)z'Create a new namespace-handling parser.r6)Znamespace_separatorT)rrLZnamespace_prefixes)rrqrrrrMs zNamespaces.createParsercCs tj|||jjr|j|_dS)z.Insert the namespace-handlers onto the parser.N)rCrOrDZnamespace_declarationsstart_namespace_decl_handlerZStartNamespaceDeclHandler)rrqrrrrOs zNamespaces.installcCs|jj||fdS)z/Push this namespace declaration on our storage.N)rr)rr@r>rrrrsz'Namespaces.start_namespace_decl_handlercCsd|krt||\}}}}nt}|}d}t}tj||||}|j|_t|j|||_|j rxZ|j D]P\}}|rtj t |d|t |d}ntj dt dt}||_ |j|_t||qdW|j dd=|r|j|j} |j} xtdt|dD]} || } || d} d| krJt|| \}}}}tj ||||}|| |<|| ||f<n$tj | t| t}|| | <|| t| f<|j|_| |_ ||_qWdS)Nr6zxmlns:xmlnsrrr)rBrrrZElementrRrr rSrrr5rrr Z_ensure_attributes_attrs_attrsNSrr9Z ownerElement)rr;rr>r?r@rArrrrrr$rrrrrsP      z Namespaces.start_element_handlerN) r.r/r0rrrMrOrrrrrrrs/rc@seZdZdZddZdS)ExpatBuilderNSz*Document builder that supports namespaces.cCstj||jdS)N)rCrJr)rrrrrJ)s zExpatBuilderNS.resetN)r.r/r0rrJrrrrr&src@s eZdZdZddZddZdS)FragmentBuilderNSz*Fragment builder that supports namespaces.cCstj||jdS)N)rrJr)rrrrrJ1s zFragmentBuilderNS.resetcCsd}|j}g}xv|rt|dr|x\|jjD]N\}}||krZdeclnamerrrr5s"    zFragmentBuilderNS._getNSattrsN)r.r/r0rrJrrrrrr.src@seZdZdZdS)rxzEException raised to short-circuit parsing in InternalSubsetExtractor.N)r.r/r0rrrrrrxSsrxc@sLeZdZdZdZddZddZddZd d Zd d Z d dZ ddZ dS)rzBXML processor which can rip out the internal document type subset.NcCs|jS)z'Return the internal subset as a string.)r)rrrrr\sz!InternalSubsetExtractor.getSubsetc Cs*ytj||Wntk r$YnXdS)N)rCr|rx)rryrrrr|`sz!InternalSubsetExtractor.parseFilec Cs*ytj||Wntk r$YnXdS)N)rCr~rx)rr}rrrr~fsz#InternalSubsetExtractor.parseStringcCs|j|_|j|_dS)N)rVrWrrY)rrqrrrrOlszInternalSubsetExtractor.installcCs0|r&|j}g|_|jj|_|j|_ntdS)N)rPrrZDefaultHandlerrrrx)rr;rrrrqrrrrVps   z2InternalSubsetExtractor.start_doctype_decl_handlercCs,dj|jjddjdd}||_tdS)Nrsz   )joinrreplacerx)rr4rrrrzsz0InternalSubsetExtractor.end_doctype_decl_handlercCs tdS)N)rx)rr;rrrrrsz-InternalSubsetExtractor.start_element_handler) r.r/r0rrrr|r~rOrVrrrrrrrWs rTc CsL|r t}nt}t|tr>t|d}|j|}WdQRXn |j|}|S)z{Parse a document, returning the resulting Document node. 'file' may be either a file name or an open file object. rbN)rrC isinstancestropenr|)ry namespacesr3fpresultrrrparses   rcCs|r t}nt}|j|S)zOParse a document from a string, returning the resulting Document node. )rrCr~)r}rr3rrrr~sr~c CsP|rt|}nt|}t|trBt|d}|j|}WdQRXn |j|}|S)zParse a fragment of a document, given the context from which it was originally extracted. context should be the parent of the node(s) which are in the fragment. 'file' may be either a file name or an open file object. rN)rrrrrr|)ryrrr3rrrrr parseFragments    rcCs |rt|}nt|}|j|S)zParse a fragment of a document from a string, given the context from which it was originally extracted. context should be the parent of the node(s) which are in the fragment. )rrr~)r}rrr3rrrparseFragmentStrings rcCs|jrt|St|SdS)z,Create a builder based on an Options object.N)rrrC)rKrrr makeBuildersr)T)T)T)T)3rZxml.domrrrrrrZ xml.parsersrZxml.dom.minidomr r Zxml.dom.NodeFilterr rrrZDOMBuilderFilterrrrrZgetDOMImplementationrQZTypeInfor"objectrr5rBrCrrFrrrrrrrrr Exceptionrxrrr~rrrrrrrs^          3C :  u_%,   __pycache__/expatbuilder.cpython-36.opt-2.pyc000064400000056672147204745200015057 0ustar003 \ @sddlmZmZmZddlmZmZmZddlmZddl m Z m Z ddl m Z ejZejZejZejjZejjZejjZejjZejZejddejddejdd ejdd ejdd ejdd ejdd ejddejddd ZGdddeZddZddZGdddZeeefZGdddeZ GdddeZ!Gddde!Z"Gdd d e!Z#d!Z$d"e$Z%Gd#d$d$eZ&Gd%d&d&Z'Gd'd(d(e'eZ(Gd)d*d*e'e&Z)Gd+d,d,e*Z+Gd-d.d.eZ,d:d0d1Z-d;d2d3Z.d) xmlbuilderminidomNode)EMPTY_NAMESPACE EMPTY_PREFIXXMLNS_NAMESPACE)expat) _append_child_set_attribute_node) NodeFilterNZcdata enumerationentityentitiesidZidrefZidrefsZnmtokenZnmtokens) ZCDATAENUMZENTITYZENTITIESIDZIDREFZIDREFSZNMTOKENZNMTOKENSc@sZeZdZdZdddZddZd d Zd d Zd dZddZ ddZ ddZ ddZ dS) ElementInfo _attr_info_modeltagNameNcCs||_g|_||_dS)N)rrr)selfrmodelr,/usr/lib64/python3.6/xml/dom/expatbuilder.py__init__?szElementInfo.__init__cCs|j|j|jfS)N)rrr)rrrr __getstate__DszElementInfo.__getstate__cCs|\|_|_|_dS)N)rrr)rstaterrr __setstate__GszElementInfo.__setstate__cCsJxB|jD]8}|d|kr|d}|ddkr4tdSt|dSqWtjS)Nr(rr!)r _typeinfo_mapr_no_type)ranameinfotrrrgetAttributeTypeJs   zElementInfo.getAttributeTypecCstjS)N)rr#)rZ namespaceURIZ localNamerrrgetAttributeTypeNSTszElementInfo.getAttributeTypeNScCs,|jr$|jd}|tjjtjjfkSdSdS)NrF)rrrZ XML_CTYPE_ANYZXML_CTYPE_MIXED)rtyperrrisElementContentWs   zElementInfo.isElementContentcCs |jr|jdtjjkSdSdS)NrF)rrrZXML_CTYPE_EMPTY)rrrrisEmpty_szElementInfo.isEmptycCs,x&|jD]}|d|kr|ddkSqWdS)NrrrFr!)r)rr$r%rrrisIdes  zElementInfo.isIdcCs|j||fS)N)r,)rZeuriZenameZaurir$rrrisIdNSkszElementInfo.isIdNS)rrr)N) __name__ __module__ __qualname__ __slots__rrrr'r(r*r+r,r-rrrrr<s  rcCs |j||S)N)_intern_setdefault)buildersrrr_internosr5cCs|jd}|j}t|dkrR|\}}}|||}d||f}|||}|||}n4t|dkrz|\}}t}|||}}n td|||||||fS)N z%s:%srz4Unsupported syntax: spaces in URIs not supported: %r)splitr2lenr ValueError)r3namepartsinternuri localnameprefixqnamerrr_parse_ns_namers         rBc@seZdZd:ddZddZddZdd Zd d Zd d ZddZ ddZ ddZ ddZ ddZ ddZddZddZddZd d!Zd"d#Zd$d%Zd&d'Zd(d)Zd*d+Zd,d-Zd.d/Zd0d1Zd2d3Zd4d5Zd6d7Zd8d9ZdS); ExpatBuilderNcCsP|dkrtj}||_|jjdk r2t|jj|_n d|_t|_d|_|j dS)N) rZOptions_optionsfilterFilterVisibilityController_filterr_finish_start_element_parserreset)roptionsrrrrs zExpatBuilder.__init__cCstjS)N)r ParserCreate)rrrr createParserszExpatBuilder.createParsercCsF|js@|j|_|jjj|_d|j_d|j_d|j_|j|j|jS)NT) rIrMr= setdefaultr2Z buffer_textZordered_attributesZspecified_attributesinstall)rrrr getParsers   zExpatBuilder.getParsercCs,tjtdd|_|j|_|jj|_d|_dS)NF)theDOMImplementationZcreateDocumentrdocumentcurNode _elem_info_cdata)rrrrrJs   zExpatBuilder.resetcCs|j|_|j|_|j|_|j|_|jj r0|j |_ |j |_ |jjrH|j|_|jjrj|j|_|j|_|j|_n|j|_|j|_|j|_|j|_|j|_ dS)N)!start_doctype_decl_handlerStartDoctypeDeclHandlerfirst_element_handlerStartElementHandlerend_element_handlerEndElementHandler pi_handlerProcessingInstructionHandlerrDrentity_decl_handlerEntityDeclHandlernotation_decl_handlerNotationDeclHandlercommentscomment_handlerCommentHandlerZcdata_sectionsstart_cdata_section_handlerStartCdataSectionHandlerend_cdata_section_handlerEndCdataSectionHandlercharacter_data_handler_cdataCharacterDataHandlercharacter_data_handlerexternal_entity_ref_handlerExternalEntityRefHandlerxml_decl_handlerZXmlDeclHandlerelement_decl_handlerZElementDeclHandlerattlist_decl_handlerZAttlistDeclHandler)rparserrrrrOs$ zExpatBuilder.installc Cs|j}d}yLx:|jd}|s P|j|d|rB|jjrB|j|d}qW|jddWntk rlYnX|j}|jd|_|S)NTirFi@) rPreadParserRdocumentElement _setup_subset ParseEscaperJrI)rfilerqZ first_bufferbufferdocrrr parseFiles$    zExpatBuilder.parseFilec CsP|j}y|j|d|j|Wntk r6YnX|j}|jd|_|S)NT)rPrurwrxrRrJrI)rstringrqr{rrr parseStrings zExpatBuilder.parseStringcCs.|jjr*t}|j||j}||jj_dS)N)rRdoctypeInternalSubsetExtractorr~ getSubsetinternalSubset)rrzZ extractorsubsetrrrrws  zExpatBuilder._setup_subsetcCs|jjj|||}|j|_t|j|||j_|jrj|jj|tkrjd|j_|jj d=d}d|j _ d|j _ |r|dk rg|j _g|j_d|j _d|j _|j|j _dS)Nr)rRimplementationZcreateDocumentType ownerDocumentr rrG acceptNode FILTER_REJECT childNodesrIr_rar_seq notationsrdr]end_doctype_decl_handlerEndDoctypeDeclHandler)rZ doctypeNamesystemIdpublicIdhas_internal_subsetrrrrrVs$   z'ExpatBuilder.start_doctype_decl_handlercCs2|jjr|j|j_|j|j_|jp&|js.t |_ dS)N) rDrbrcrIrdr\r]rTrGr_finish_end_element)rrrrrs    z%ExpatBuilder.end_doctype_decl_handlercCs@|jj||}t|j||jr<|jj|tkr<|jj|dS)N)rRZcreateProcessingInstructionr rSrGrr removeChild)rtargetdatanoderrrr\ s zExpatBuilder.pi_handlercCs|jj}|jrH|jr4|djtkr4|dj|dS|jj|}d|_nD|rv|djt krv|d}|j |}||_ dSt j }||_ |j|_ t|j|dS)NrTrrrr)rSrrU_cdata_continuenodeTypeCDATA_SECTION_NODEZ appendDatarRZcreateCDATASection TEXT_NODErrTextrr )rrrrvaluerrrris"  z)ExpatBuilder.character_data_handler_cdatacCs^|jj}|r2|djtkr2|d}|j||_dStj}|j||_|j|_t |j|dS)Nrrr) rSrrrrrrrRrr )rrrrrrrrk&s  z#ExpatBuilder.character_data_handlerc Cs|rdS|jjsdS|jj||||}|dk rF|jj|} |jj| |jjjjj||j r||j j |t kr||jjjjd=dS)Nrr) rDrrRZ_create_entityZcreateTextNoderappendrrrGrr) rZ entityNameZis_parameter_entityrbaserr notationNamerchildrrrr^1s   z ExpatBuilder.entity_decl_handlercCsJ|jj|||}|jjjjj||jrF|jj|tkrF|jjjjd=dS)Nrr) rRZ_create_notationrrrrrGr FILTER_ACCEPT)rrrrrrrrrr`Csz"ExpatBuilder.notation_decl_handlercCs>|jj|}t|j||jr:|jj|tkr:|jj|dS)N)rRZ createCommentr rSrGrrr)rrrrrrrcIs  zExpatBuilder.comment_handlercCsd|_d|_dS)NTF)rUr)rrrrreOsz(ExpatBuilder.start_cdata_section_handlercCsd|_d|_dS)NF)rUr)rrrrrgSsz&ExpatBuilder.end_cdata_section_handlercCsdS)Nrr)rcontextrrrrrrrlWsz(ExpatBuilder.external_entity_ref_handlercCs4|jdkr|j rt|_|j|j_|j||dS)N)rGrTrrstart_element_handlerrPrY)rr; attributesrrrrXZs z"ExpatBuilder.first_element_handlercCs|jj|}t|j|||_|rtxPtdt|dD]<}tj||tdt }||d}||_ |j|_ t ||q4W||jj k r|j|dS)Nrrr)rRZ createElementr rSranger9rAttrrrrrr rvrH)rr;rriarrrrr`s     z"ExpatBuilder.start_element_handlercCsj|jrf||jjkrdS|jj|}|tkr4t|n|tkrFt|ndS|j|_ |jj ||j dS)N) rGrRrvstartContainerrRejecter FILTER_SKIPSkipper parentNoderSrunlink)rrZfiltrrrrHqs     z"ExpatBuilder._finish_start_elementcCs|j}|j|_|j|dS)N)rSrr)rr;rSrrrrZsz ExpatBuilder.end_element_handlercCs\|jj|j}|r|j|||jrX||jjkr4dS|jj|tkrX|j j ||j dS)N) rTgetr_handle_white_text_nodesrGrRrvrrrSrr)rrSr%rrrrs   z ExpatBuilder._finish_end_elementcCsf|jjs|j rdSg}x.|jD]$}|jtkr"|jj r"|j|q"Wx|D]}|j |qPWdS)N) rDZwhitespace_in_element_contentr*rrrrstriprr)rrr%Lrrrrrs   z%ExpatBuilder._handle_white_text_nodescCs0|jj|}|dkr&t|||j|<n||_dS)N)rTrrr)rr;rr%rrrros z!ExpatBuilder.element_decl_handlerc CsF|jj|}|dkr&t|}||j|<|jjd|dd|d||gdS)Nr)rTrrrr)relemr;r)defaultZrequiredr%rrrrps   z!ExpatBuilder.attlist_decl_handlercCs2||j_||j_|dkr.|r&d|j_nd|j_dS)NrTF)rRversionencoding standalone)rrrrrrrrns  zExpatBuilder.xml_decl_handler)N)r.r/r0rrMrPrJrOr|r~rwrVrr\rirkr^r`rcrergrlrXrrHrZrrrorprnrrrrrCs8     rCc@seZdZd ZddZddZddZeje j ej e j ej e jeje jeje jeje jeje jeje jeje jeje jeje jeje j i Z!dS) rFrEcCs ||_dS)N)rE)rrErrrrsz#FilterVisibilityController.__init__cCsT|j|j}|jj|@rL|jj|}|tkr0t|tkrHtdt ||St SdS)Nz)startContainer() returned illegal value: ) _nodetype_maskrrE whatToShowrFILTER_INTERRUPTrx_ALLOWED_FILTER_RETURNSr:reprr)rrmaskvalrrrrs   z)FilterVisibilityController.startContainercCs|j|j}|jj|@r|jj|}|tkr0t|tkrd|j}x |j ddD]}|j |qNWt S|t kr|t dt||StSdS)Nz%acceptNode() returned illegal value: )rrrErrrrxrrrZ appendChildrrr:rr)rrrrparentrrrrrs   z%FilterVisibilityController.acceptNodeN)rE)"r.r/r0r1rrrrZ ELEMENT_NODEr Z SHOW_ELEMENTZATTRIBUTE_NODEZSHOW_ATTRIBUTErZ SHOW_TEXTrZSHOW_CDATA_SECTIONZENTITY_REFERENCE_NODEZSHOW_ENTITY_REFERENCEZ ENTITY_NODEZ SHOW_ENTITYZPROCESSING_INSTRUCTION_NODEZSHOW_PROCESSING_INSTRUCTIONZ COMMENT_NODEZ SHOW_COMMENT DOCUMENT_NODEZ SHOW_DOCUMENTZDOCUMENT_TYPE_NODEZSHOW_DOCUMENT_TYPEZDOCUMENT_FRAGMENT_NODEZSHOW_DOCUMENT_FRAGMENTZ NOTATION_NODEZ SHOW_NOTATIONrrrrrrFs  rFc@seZdZdZddZdS) FilterCrutch_builder_level _old_start_old_endcCs6d|_||_|j}|j|_|j|_|j|_|j|_dS)Nr) rrrIrYrr[rrrZ)rr3rqrrrrszFilterCrutch.__init__N)rrrr)r.r/r0r1rrrrrrsrc@s(eZdZfZddZddZddZdS)rcCs0tj|||j}xdD]}t||dqWdS)Nr]rdrjrfrhrm)r]rdrjrfrhrm)rrrIsetattr)rr3rqr;rrrrs zRejecter.__init__cGs|jd|_dS)Nr)r)rargsrrrrszRejecter.start_element_handlercGs@|jdkr0|jj}|jj||j|_|j|_n |jd|_dS)Nrr)rrrIrOrrYrr[)rrrqrrrrZ s    zRejecter.end_element_handlerN)r.r/r0r1rrrZrrrrrs rc@s eZdZfZddZddZdS)rcGs.|jj}|j||jj|k r*|jd|_dS)Nr)rrSrr)rrrrrrr-s  zSkipper.start_element_handlercGsD|jdkr*|j|jj_|j|jj_d|_n|jd|_|j|dS)Nrr)rrrrIrYrr[)rrrrrrZ3s     zSkipper.end_element_handlerN)r.r/r0r1rrZrrrrr*srz8http://xml.python.org/entities/fragment-builder/internalz %%s ]> &fragment-builder-internal;c@sFeZdZdddZddZddZdd Zd d Zd d ZddZ dS)FragmentBuilderNcCs6|jtkr||_||_n|j|_||_tj||dS)N)rroriginalDocumentrrrCr)rrrKrrrr[s  zFragmentBuilder.__init__cCstj|d|_dS)N)rCrJfragment)rrrrrJds zFragmentBuilder.resetcCs|j|jS)N)r~rt)rryrrrr|hszFragmentBuilder.parseFilec Cs||_|j}|jj}d}|rV|jp*|j}|jrDd|j|jf}qZ|jrZd|j}nd}|j}t |||f}y|j |dWn|j YnX|j }|j |S)NrszPUBLIC "%s" "%s"z SYSTEM "%s"r) _sourcerPrrr_getDeclarationsrr _getNSattrs_FRAGMENT_BUILDER_TEMPLATErurJr) rr}rqrZidentrZnsattrsrRrrrrr~ms, zFragmentBuilder.parseStringcCs|jjj}d}|rxbt|jjD]R}|jj|}|r>|d}d||jf}|jrfd||j|j f}q"d||j f}q"Wxt|j jD]}|j j|}|r|d}d||jf}|jrd||j|j f}n&|j rd||j f}nd ||j j f}|j rd ||j f}|d }qW|S) Nrsz z%sz%s SYSTEM "%s">z %s)rrrrrZlengthitemZnodeNamerrrZ firstChildrr)rrr4rZnotationr rrrrs6    z FragmentBuilder._getDeclarationscCsdS)Nrsr)rrrrrszFragmentBuilder._getNSattrsc Cs~|tkrh|j}|j}|jj|}|j|_|jj|_|j|_z|j|j dWd||_||_d|_ XdSt j |||||SdS)Nrr) $_FRAGMENT_BUILDER_INTERNAL_SYSTEM_IDrRrSrIZExternalEntityParserCreaterZcreateDocumentFragmentrrurrCrl)rrrrrZ old_documentZ old_cur_noderqrrrrls  z+FragmentBuilder.external_entity_ref_handler)N) r.r/r0rrJr|r~rrrlrrrrrRs $rc@s4eZdZddZddZddZddZd d Zd S) NamespacescCs g|_dS)N)_ns_ordered_prefixes)rrrr_initNamespacesszNamespaces._initNamespacescCstjdd}d|_|S)Nr6)Znamespace_separatorT)rrLZnamespace_prefixes)rrqrrrrMs zNamespaces.createParsercCs tj|||jjr|j|_dS)N)rCrOrDZnamespace_declarationsstart_namespace_decl_handlerZStartNamespaceDeclHandler)rrqrrrrOs zNamespaces.installcCs|jj||fdS)N)rr)rr@r>rrrrsz'Namespaces.start_namespace_decl_handlercCsd|krt||\}}}}nt}|}d}t}tj||||}|j|_t|j|||_|j rxZ|j D]P\}}|rtj t |d|t |d}ntj dt dt}||_ |j|_t||qdW|j dd=|r|j|j} |j} xtdt|dD]} || } || d} d| krJt|| \}}}}tj ||||}|| |<|| ||f<n$tj | t| t}|| | <|| t| f<|j|_| |_ ||_qWdS)Nr6zxmlns:xmlnsrrr)rBrrrZElementrRrr rSrrr5rrr Z_ensure_attributes_attrs_attrsNSrr9Z ownerElement)rr;rr>r?r@rArrrrrr$rrrrrsP      z Namespaces.start_element_handlerN)r.r/r0rrMrOrrrrrrrs /rc@seZdZddZdS)ExpatBuilderNScCstj||jdS)N)rCrJr)rrrrrJ)s zExpatBuilderNS.resetN)r.r/r0rJrrrrr&src@seZdZddZddZdS)FragmentBuilderNScCstj||jdS)N)rrJr)rrrrrJ1s zFragmentBuilderNS.resetcCsd}|j}g}xv|rt|dr|x\|jjD]N\}}||krZdeclnamerrrr5s"    zFragmentBuilderNS._getNSattrsN)r.r/r0rJrrrrrr.src@s eZdZdS)rxN)r.r/r0rrrrrxSsrxc@sHeZdZdZddZddZddZdd Zd d Zd d Z ddZ dS)rNcCs|jS)N)r)rrrrr\sz!InternalSubsetExtractor.getSubsetc Cs*ytj||Wntk r$YnXdS)N)rCr|rx)rryrrrr|`sz!InternalSubsetExtractor.parseFilec Cs*ytj||Wntk r$YnXdS)N)rCr~rx)rr}rrrr~fsz#InternalSubsetExtractor.parseStringcCs|j|_|j|_dS)N)rVrWrrY)rrqrrrrOlszInternalSubsetExtractor.installcCs0|r&|j}g|_|jj|_|j|_ntdS)N)rPrrZDefaultHandlerrrrx)rr;rrrrqrrrrVps   z2InternalSubsetExtractor.start_doctype_decl_handlercCs,dj|jjddjdd}||_tdS)Nrsz   )joinrreplacerx)rr4rrrrzsz0InternalSubsetExtractor.end_doctype_decl_handlercCs tdS)N)rx)rr;rrrrrsz-InternalSubsetExtractor.start_element_handler) r.r/r0rrr|r~rOrVrrrrrrrWs rTc CsL|r t}nt}t|tr>t|d}|j|}WdQRXn |j|}|S)Nrb)rrC isinstancestropenr|)ry namespacesr3fpresultrrrparses   rcCs|r t}nt}|j|S)N)rrCr~)r}rr3rrrr~sr~c CsP|rt|}nt|}t|trBt|d}|j|}WdQRXn |j|}|S)Nr)rrrrrr|)ryrrr3rrrrr parseFragments    rcCs |rt|}nt|}|j|S)N)rrr~)r}rrr3rrrparseFragmentStrings rcCs|jrt|St|SdS)N)rrrC)rKrrr makeBuildersr)T)T)T)T)2Zxml.domrrrrrrZ xml.parsersrZxml.dom.minidomr r Zxml.dom.NodeFilterr rrrZDOMBuilderFilterrrrrZgetDOMImplementationrQZTypeInfor"objectrr5rBrCrrFrrrrrrrrr Exceptionrxrrr~rrrrrrrs\          3C :  u_%,   __pycache__/expatbuilder.cpython-36.pyc000064400000065012147204745200014103 0ustar003 \ @sdZddlmZmZmZddlmZmZmZddlm Z ddl m Z m Z ddl mZejZejZejZejjZejjZejjZejjZejZejddejdd ejdd ejdd ejdd ejdd ejddejddejddd ZGdddeZddZddZGdddZeeefZ GdddeZ!GdddeZ"Gddde"Z#Gd d!d!e"Z$d"Z%d#e%Z&Gd$d%d%eZ'Gd&d'd'Z(Gd(d)d)e(eZ)Gd*d+d+e(e'Z*Gd,d-d-e+Z,Gd.d/d/eZ-d;d1d2Z.dd7d8Z1d9d:Z2dS)?zFacility to use the Expat parser to load a minidom instance from a string or file. This avoids all the overhead of SAX and pulldom to gain performance. ) xmlbuilderminidomNode)EMPTY_NAMESPACE EMPTY_PREFIXXMLNS_NAMESPACE)expat) _append_child_set_attribute_node) NodeFilterNZcdata enumerationentityentitiesidZidrefZidrefsZnmtokenZnmtokens) ZCDATAENUMZENTITYZENTITIESIDZIDREFZIDREFSZNMTOKENZNMTOKENSc@sZeZdZdZdddZddZd d Zd d Zd dZddZ ddZ ddZ ddZ dS) ElementInfo _attr_info_modeltagNameNcCs||_g|_||_dS)N)rrr)selfrmodelr,/usr/lib64/python3.6/xml/dom/expatbuilder.py__init__?szElementInfo.__init__cCs|j|j|jfS)N)rrr)rrrr __getstate__DszElementInfo.__getstate__cCs|\|_|_|_dS)N)rrr)rstaterrr __setstate__GszElementInfo.__setstate__cCsJxB|jD]8}|d|kr|d}|ddkr4tdSt|dSqWtjS)Nr(rr!)r _typeinfo_mapr_no_type)ranameinfotrrrgetAttributeTypeJs   zElementInfo.getAttributeTypecCstjS)N)rr#)r namespaceURI localNamerrrgetAttributeTypeNSTszElementInfo.getAttributeTypeNScCs,|jr$|jd}|tjjtjjfkSdSdS)NrF)rrrZ XML_CTYPE_ANYZXML_CTYPE_MIXED)rtyperrrisElementContentWs   zElementInfo.isElementContentcCs |jr|jdtjjkSdSdS)NrF)rrrZXML_CTYPE_EMPTY)rrrrisEmpty_szElementInfo.isEmptycCs,x&|jD]}|d|kr|ddkSqWdS)NrrrFr!)r)rr$r%rrrisIdes  zElementInfo.isIdcCs|j||fS)N)r.)rZeuriZenameZaurir$rrrisIdNSkszElementInfo.isIdNS)rrr)N) __name__ __module__ __qualname__ __slots__rrrr'r*r,r-r.r/rrrrr<s  rcCs |j||S)N)_intern_setdefault)buildersrrr_internosr7cCsd|ks t|jd}|j}t|dkr^|\}}}|||}d||f}|||}|||}n4t|dkr|\}}t}|||}}n td|||||||fS)N z%s:%srz4Unsupported syntax: spaces in URIs not supported: %r)AssertionErrorsplitr4lenr ValueError)r5namepartsinternuri localnameprefixqnamerrr_parse_ns_namers          rEc@seZdZdZd;ddZddZddZd d Zd d Zd dZ ddZ ddZ ddZ ddZ ddZddZddZddZdd Zd!d"Zd#d$Zd%d&Zd'd(Zd)d*Zd+d,Zd-d.Zd/d0Zd1d2Zd3d4Zd5d6Zd7d8Zd9d:ZdS)< ExpatBuilderzPDocument builder that uses Expat to build a ParsedXML.DOM document instance.NcCsP|dkrtj}||_|jjdk r2t|jj|_n d|_t|_d|_|j dS)N) rZOptions_optionsfilterFilterVisibilityController_filterr_finish_start_element_parserreset)roptionsrrrrs zExpatBuilder.__init__cCstjS)zCreate a new parser object.)r ParserCreate)rrrr createParserszExpatBuilder.createParsercCsF|js@|j|_|jjj|_d|j_d|j_d|j_|j|j|jS)z7Return the parser object, creating a new one if needed.T) rLrPr@ setdefaultr4Z buffer_textZordered_attributesZspecified_attributesinstall)rrrr getParsers   zExpatBuilder.getParsercCs,tjtdd|_|j|_|jj|_d|_dS)z6Free all data structures used during DOM construction.NF)theDOMImplementationZcreateDocumentrdocumentcurNode _elem_info_cdata)rrrrrMs   zExpatBuilder.resetcCs|j|_|j|_|j|_|j|_|jj r0|j |_ |j |_ |jjrH|j|_|jjrj|j|_|j|_|j|_n|j|_|j|_|j|_|j|_|j|_ dS)z>Install the callbacks needed to build the DOM into the parser.N)!start_doctype_decl_handlerStartDoctypeDeclHandlerfirst_element_handlerStartElementHandlerend_element_handlerEndElementHandler pi_handlerProcessingInstructionHandlerrGrentity_decl_handlerEntityDeclHandlernotation_decl_handlerNotationDeclHandlercommentscomment_handlerCommentHandlerZcdata_sectionsstart_cdata_section_handlerStartCdataSectionHandlerend_cdata_section_handlerEndCdataSectionHandlercharacter_data_handler_cdataCharacterDataHandlercharacter_data_handlerexternal_entity_ref_handlerExternalEntityRefHandlerxml_decl_handlerZXmlDeclHandlerelement_decl_handlerZElementDeclHandlerattlist_decl_handlerZAttlistDeclHandler)rparserrrrrRs$ zExpatBuilder.installc Cs|j}d}yLx:|jd}|s P|j|d|rB|jjrB|j|d}qW|jddWntk rlYnX|j}|jd|_|S) zIParse a document from a file object, returning the document node.TirFNi@) rSreadParserUdocumentElement _setup_subset ParseEscaperMrL)rfilertZ first_bufferbufferdocrrr parseFiles$    zExpatBuilder.parseFilec CsP|j}y|j|d|j|Wntk r6YnX|j}|jd|_|S)z|jj|}t|j||jr:|jj|tkr:|jj|dS)N)rUZ createCommentr rVrJrrr)rrrrrrrfIs  zExpatBuilder.comment_handlercCsd|_d|_dS)NTF)rXr)rrrrrhOsz(ExpatBuilder.start_cdata_section_handlercCsd|_d|_dS)NF)rXr)rrrrrjSsz&ExpatBuilder.end_cdata_section_handlercCsdS)Nrr)rcontextrrrrrrroWsz(ExpatBuilder.external_entity_ref_handlercCs4|jdkr|j rt|_|j|j_|j||dS)N)rJrWrrstart_element_handlerrSr\)rr> attributesrrrr[Zs z"ExpatBuilder.first_element_handlercCs|jj|}t|j|||_|rtxPtdt|dD]<}tj||tdt }||d}||_ |j|_ t ||q4W||jj k r|j|dS)Nrrr)rUZ createElementr rVranger<rAttrrrrrr ryrK)rr>rriarrrrr`s     z"ExpatBuilder.start_element_handlercCsj|jrf||jjkrdS|jj|}|tkr4t|n|tkrFt|ndS|j|_ |jj ||j dS)N) rJrUrystartContainerrRejecter FILTER_SKIPSkipper parentNoderVrunlink)rrZfiltrrrrKqs     z"ExpatBuilder._finish_start_elementcCs|j}|j|_|j|dS)N)rVrr)rr>rVrrrr]sz ExpatBuilder.end_element_handlercCs\|jj|j}|r|j|||jrX||jjkr4dS|jj|tkrX|j j ||j dS)N) rWgetr_handle_white_text_nodesrJrUryrrrVrr)rrVr%rrrrs   z ExpatBuilder._finish_end_elementcCsf|jjs|j rdSg}x.|jD]$}|jtkr"|jj r"|j|q"Wx|D]}|j |qPWdS)N) rGZwhitespace_in_element_contentr,rrrrstriprr)rrr%Lrrrrrs   z%ExpatBuilder._handle_white_text_nodescCs>|jj|}|dkr&t|||j|<n|jdks4t||_dS)N)rWrrrr:)rr>rr%rrrrrs  z!ExpatBuilder.element_decl_handlerc CsF|jj|}|dkr&t|}||j|<|jjd|dd|d||gdS)Nr)rWrrrr)relemr>r+defaultZrequiredr%rrrrss   z!ExpatBuilder.attlist_decl_handlercCs2||j_||j_|dkr.|r&d|j_nd|j_dS)NrTF)rUversionencoding standalone)rrrrrrrrqs  zExpatBuilder.xml_decl_handler)N) r0r1r2__doc__rrPrSrMrRrrrzrYrr_rlrnrarcrfrhrjror[rrKr]rrrrrsrqrrrrrFs:     rFc@seZdZdZd ZddZddZddZej e j ej e j eje jeje jeje jeje jeje jeje jeje jeje jeje jej e j!i Z"d S) rIzoWrapper around a DOMBuilderFilter which implements the checks to make the whatToShow filter attribute work.rHcCs ||_dS)N)rH)rrHrrrrsz#FilterVisibilityController.__init__cCsT|j|j}|jj|@rL|jj|}|tkr0t|tkrHtdt ||St SdS)Nz)startContainer() returned illegal value: ) _nodetype_maskrrH whatToShowrFILTER_INTERRUPTr{_ALLOWED_FILTER_RETURNSr=reprr)rrmaskvalrrrrs   z)FilterVisibilityController.startContainercCs|j|j}|jj|@r|jj|}|tkr0t|tkrd|j}x |j ddD]}|j |qNWt S|t kr|t dt||StSdS)Nz%acceptNode() returned illegal value: )rrrHrrrr{rrrZ appendChildrrr=rr)rrrrparentrrrrrs   z%FilterVisibilityController.acceptNodeN)rH)#r0r1r2rr3rrrrZ ELEMENT_NODEr Z SHOW_ELEMENTZATTRIBUTE_NODEZSHOW_ATTRIBUTErZ SHOW_TEXTrZSHOW_CDATA_SECTIONZENTITY_REFERENCE_NODEZSHOW_ENTITY_REFERENCEZ ENTITY_NODEZ SHOW_ENTITYZPROCESSING_INSTRUCTION_NODEZSHOW_PROCESSING_INSTRUCTIONZ COMMENT_NODEZ SHOW_COMMENT DOCUMENT_NODEZ SHOW_DOCUMENTZDOCUMENT_TYPE_NODEZSHOW_DOCUMENT_TYPEZDOCUMENT_FRAGMENT_NODEZSHOW_DOCUMENT_FRAGMENTZ NOTATION_NODEZ SHOW_NOTATIONrrrrrrIs" rIc@seZdZdZddZdS) FilterCrutch_builder_level _old_start_old_endcCs6d|_||_|j}|j|_|j|_|j|_|j|_dS)Nr) rrrLr\rr^rrr])rr5rtrrrrszFilterCrutch.__init__N)rrrr)r0r1r2r3rrrrrrsrc@s(eZdZfZddZddZddZdS)rcCs0tj|||j}xdD]}t||dqWdS)Nr`rgrmrirkrp)r`rgrmrirkrp)rrrLsetattr)rr5rtr>rrrrs zRejecter.__init__cGs|jd|_dS)Nr)r)rargsrrrrszRejecter.start_element_handlercGs@|jdkr0|jj}|jj||j|_|j|_n |jd|_dS)Nrr)rrrLrRrr\rr^)rrrtrrrr] s    zRejecter.end_element_handlerN)r0r1r2r3rrr]rrrrrs rc@s eZdZfZddZddZdS)rcGs.|jj}|j||jj|k r*|jd|_dS)Nr)rrVrr)rrrrrrr-s  zSkipper.start_element_handlercGsD|jdkr*|j|jj_|j|jj_d|_n|jd|_|j|dS)Nrr)rrrrLr\rr^)rrrrrr]3s     zSkipper.end_element_handlerN)r0r1r2r3rr]rrrrr*srz8http://xml.python.org/entities/fragment-builder/internalz %%s ]> &fragment-builder-internal;c@sJeZdZdZdddZddZddZd d Zd d Zd dZ ddZ dS)FragmentBuilderzBuilder which constructs document fragments given XML source text and a context node. The context node is expected to provide information about the namespace declarations which are in scope at the start of the fragment. NcCs6|jtkr||_||_n|j|_||_tj||dS)N)rroriginalDocumentrrrFr)rrrNrrrr[s  zFragmentBuilder.__init__cCstj|d|_dS)N)rFrMfragment)rrrrrMds zFragmentBuilder.resetcCs|j|jS)zRParse a document fragment from a file object, returning the fragment node.)rrw)rr|rrrrhszFragmentBuilder.parseFilec Cs||_|j}|jj}d}|rV|jp*|j}|jrDd|j|jf}qZ|jrZd|j}nd}|j}t |||f}y|j |dWn|j YnX|j }|j |S)zMParse a document fragment from a string, returning the fragment node.rvzPUBLIC "%s" "%s"z SYSTEM "%s"r) _sourcerSrrr_getDeclarationsrr _getNSattrs_FRAGMENT_BUILDER_TEMPLATErxrMr) rrrtrZidentrZnsattrsrUrrrrrms, zFragmentBuilder.parseStringcCs|jjj}d}|rxbt|jjD]R}|jj|}|r>|d}d||jf}|jrfd||j|j f}q"d||j f}q"Wxt|j jD]}|j j|}|r|d}d||jf}|jrd||j|j f}n&|j rd||j f}nd ||j j f}|j rd ||j f}|d }qW|S) zRe-create the internal subset from the DocumentType node. This is only needed if we don't already have the internalSubset as a string. rvz z%sz%s SYSTEM "%s">z %s)rrrrrZlengthitemnodeNamerrrZ firstChildrr)rrr6rZnotationr rrrrs6    z FragmentBuilder._getDeclarationscCsdS)Nrvr)rrrrrszFragmentBuilder._getNSattrsc Cs~|tkrh|j}|j}|jj|}|j|_|jj|_|j|_z|j|j dWd||_||_d|_ XdSt j |||||SdS)Nrr) $_FRAGMENT_BUILDER_INTERNAL_SYSTEM_IDrUrVrLZExternalEntityParserCreaterZcreateDocumentFragmentrrxrrFro)rrrrrZ old_documentZ old_cur_nodertrrrros  z+FragmentBuilder.external_entity_ref_handler)N) r0r1r2rrrMrrrrrorrrrrRs $rc@s@eZdZdZddZddZddZdd Zd d Zd d Z dS) Namespacesz7Mix-in class for builders; adds support for namespaces.cCs g|_dS)N)_ns_ordered_prefixes)rrrr_initNamespacesszNamespaces._initNamespacescCstjdd}d|_|S)z'Create a new namespace-handling parser.r8)Znamespace_separatorT)rrOZnamespace_prefixes)rrtrrrrPs zNamespaces.createParsercCs tj|||jjr|j|_dS)z.Insert the namespace-handlers onto the parser.N)rFrRrGZnamespace_declarationsstart_namespace_decl_handlerZStartNamespaceDeclHandler)rrtrrrrRs zNamespaces.installcCs|jj||fdS)z/Push this namespace declaration on our storage.N)rr)rrCrArrrrsz'Namespaces.start_namespace_decl_handlercCsd|krt||\}}}}nt}|}d}t}tj||||}|j|_t|j|||_|j rxZ|j D]P\}}|rtj t |d|t |d}ntj dt dt}||_ |j|_t||qdW|j dd=|r|j|j} |j} xtdt|dD]} || } || d} d| krJt|| \}}}}tj ||||}|| |<|| ||f<n$tj | t| t}|| | <|| t| f<|j|_| |_ ||_qWdS)Nr8zxmlns:xmlnsrrr)rErrrZElementrUrr rVrrr7rrr Z_ensure_attributes_attrs_attrsNSrr<Z ownerElement)rr>rrArBrCrDrrrrrr$rrrrrsP      z Namespaces.start_element_handlercCs|j}d|krHt||\}}}}|j|kr>|j|kr>|j|ksltdn$|j|ksZtd|jtksltd|j|_|j |dS)Nr8z$element stack messed up! (namespace)z&element stack messed up - bad nodeNamez*element stack messed up - bad namespaceURI) rVrEr(r)rCr:rrrr)rr>rVrArBrCrDrrrr]s     zNamespaces.end_element_handlerN) r0r1r2rrrPrRrrr]rrrrrs5rc@seZdZdZddZdS)ExpatBuilderNSz*Document builder that supports namespaces.cCstj||jdS)N)rFrMr)rrrrrM)s zExpatBuilderNS.resetN)r0r1r2rrMrrrrr&src@s eZdZdZddZddZdS)FragmentBuilderNSz*Fragment builder that supports namespaces.cCstj||jdS)N)rrMr)rrrrrM1s zFragmentBuilderNS.resetcCsd}|j}g}xv|rt|dr|x\|jjD]N\}}||krrrrrtrrrrYps   z2InternalSubsetExtractor.start_doctype_decl_handlercCs,dj|jjddjdd}||_tdS)Nrvz   )joinrreplacer{)rr6rrrrzsz0InternalSubsetExtractor.end_doctype_decl_handlercCs tdS)N)r{)rr>rrrrrsz-InternalSubsetExtractor.start_element_handler) r0r1r2rrrrrrRrYrrrrrrrWs rTc CsL|r t}nt}t|tr>t|d}|j|}WdQRXn |j|}|S)z{Parse a document, returning the resulting Document node. 'file' may be either a file name or an open file object. rbN)rrF isinstancestropenr)r| namespacesr5fpresultrrrparses   rcCs|r t}nt}|j|S)zOParse a document from a string, returning the resulting Document node. )rrFr)rrr5rrrrsrc CsP|rt|}nt|}t|trBt|d}|j|}WdQRXn |j|}|S)zParse a fragment of a document, given the context from which it was originally extracted. context should be the parent of the node(s) which are in the fragment. 'file' may be either a file name or an open file object. rN)rrrrrr)r|rrr5rrrrr parseFragments    rcCs |rt|}nt|}|j|S)zParse a fragment of a document from a string, given the context from which it was originally extracted. context should be the parent of the node(s) which are in the fragment. )rrr)rrrr5rrrparseFragmentStrings rcCs|jrt|St|SdS)z,Create a builder based on an Options object.N)rrrF)rNrrr makeBuildersr)T)T)T)T)3rZxml.domrrrrrrZ xml.parsersrZxml.dom.minidomr r Zxml.dom.NodeFilterr rrrZDOMBuilderFilterrrrrZgetDOMImplementationrTZTypeInfor"objectrr7rErFrrIrrrrrrrrr Exceptionr{rrrrrrrrrrs^          3C :  u_%,   __pycache__/minicompat.cpython-36.opt-1.pyc000064400000005213147204745200014507 0ustar003 \' @sJdZddddgZddlZefZGdddeZGdddeZ d dZ dS) zPython version compatibility support for minidom. This module contains internal implementation details and should not be imported; use xml.dom.minidom instead. NodeList EmptyNodeList StringTypes defpropertyNc@s>eZdZfZddZddZddZeeeddZd d Z d S) rcCs(d|kot|knr$||SdS)Nr)len)selfindexr */usr/lib64/python3.6/xml/dom/minicompat.pyitem5sz NodeList.itemcCst|S)N)r)rr r r _get_length9szNodeList._get_lengthcCstjjddS)Nz.attempt to modify read-only attribute 'length')xmldomNoModificationAllowedErr)rvaluer r r _set_length<szNodeList._set_lengthz$The number of nodes in the NodeList.)doccCs|dkr g}||dd<dS)Nr )rstater r r __setstate__DszNodeList.__setstate__N) __name__ __module__ __qualname__ __slots__r r rpropertylengthrr r r r r2sc@sFeZdZfZddZddZddZddZd d Ze eed d Z d S)rcCst}|j||S)N)rextend)rotherNLr r r __add__Ms zEmptyNodeList.__add__cCst}|j||S)N)rr)rrrr r r __radd__Rs zEmptyNodeList.__radd__cCsdS)Nr )rrr r r r WszEmptyNodeList.itemcCsdS)Nrr )rr r r r ZszEmptyNodeList._get_lengthcCstjjddS)Nz.attempt to modify read-only attribute 'length')r rr)rrr r r r]szEmptyNodeList._set_lengthz$The number of nodes in the NodeList.)rN) rrrrrrr r rrrr r r r rJscCs8t|d|}|fdd}t|||d}t|||dS)NZ_get_cSstjjdt|dS)Nz&attempt to modify read-only attribute )r rrrepr)rrnamer r r setgszdefproperty..set)r)getattrrsetattr)klassr!rgetr"Zpropr r r res ) __doc____all__Zxml.domr strrlistrtuplerrr r r r s & __pycache__/minicompat.cpython-36.opt-2.pyc000064400000004731147204745200014514 0ustar003 \' @sFddddgZddlZefZGdddeZGdddeZddZ dS) NodeList EmptyNodeList StringTypes defpropertyNc@s>eZdZfZddZddZddZeeeddZd d Z d S) rcCs(d|kot|knr$||SdS)Nr)len)selfindexr */usr/lib64/python3.6/xml/dom/minicompat.pyitem5sz NodeList.itemcCst|S)N)r)rr r r _get_length9szNodeList._get_lengthcCstjjddS)Nz.attempt to modify read-only attribute 'length')xmldomNoModificationAllowedErr)rvaluer r r _set_length<szNodeList._set_lengthz$The number of nodes in the NodeList.)doccCs|dkr g}||dd<dS)Nr )rstater r r __setstate__DszNodeList.__setstate__N) __name__ __module__ __qualname__ __slots__r r rpropertylengthrr r r r r2sc@sFeZdZfZddZddZddZddZd d Ze eed d Z d S)rcCst}|j||S)N)rextend)rotherNLr r r __add__Ms zEmptyNodeList.__add__cCst}|j||S)N)rr)rrrr r r __radd__Rs zEmptyNodeList.__radd__cCsdS)Nr )rrr r r r WszEmptyNodeList.itemcCsdS)Nrr )rr r r r ZszEmptyNodeList._get_lengthcCstjjddS)Nz.attempt to modify read-only attribute 'length')r rr)rrr r r r]szEmptyNodeList._set_lengthz$The number of nodes in the NodeList.)rN) rrrrrrr r rrrr r r r rJscCs8t|d|}|fdd}t|||d}t|||dS)NZ_get_cSstjjdt|dS)Nz&attempt to modify read-only attribute )r rrrepr)rrnamer r r setgszdefproperty..set)r)getattrrsetattr)klassr!rgetr"Zpropr r r res ) __all__Zxml.domr strrlistrtuplerrr r r r +s __pycache__/minicompat.cpython-36.pyc000064400000005347147204745200013560 0ustar003 \' @sJdZddddgZddlZefZGdddeZGdddeZ d dZ dS) zPython version compatibility support for minidom. This module contains internal implementation details and should not be imported; use xml.dom.minidom instead. NodeList EmptyNodeList StringTypes defpropertyNc@s>eZdZfZddZddZddZeeeddZd d Z d S) rcCs(d|kot|knr$||SdS)Nr)len)selfindexr */usr/lib64/python3.6/xml/dom/minicompat.pyitem5sz NodeList.itemcCst|S)N)r)rr r r _get_length9szNodeList._get_lengthcCstjjddS)Nz.attempt to modify read-only attribute 'length')xmldomNoModificationAllowedErr)rvaluer r r _set_length<szNodeList._set_lengthz$The number of nodes in the NodeList.)doccCs|dkr g}||dd<dS)Nr )rstater r r __setstate__DszNodeList.__setstate__N) __name__ __module__ __qualname__ __slots__r r rpropertylengthrr r r r r2sc@sFeZdZfZddZddZddZddZd d Ze eed d Z d S)rcCst}|j||S)N)rextend)rotherNLr r r __add__Ms zEmptyNodeList.__add__cCst}|j||S)N)rr)rrrr r r __radd__Rs zEmptyNodeList.__radd__cCsdS)Nr )rrr r r r WszEmptyNodeList.itemcCsdS)Nrr )rr r r r ZszEmptyNodeList._get_lengthcCstjjddS)Nz.attempt to modify read-only attribute 'length')r rr)rrr r r r]szEmptyNodeList._set_lengthz$The number of nodes in the NodeList.)rN) rrrrrrr r rrrr r r r rJscCsTt|d|}|fdd}t|d| s6td|t|||d}t|||dS)NZ_get_cSstjjdt|dS)Nz&attempt to modify read-only attribute )r rrrepr)rrnamer r r setgszdefproperty..setZ_set_zexpected not to find _set_)r)getattrhasattrAssertionErrorrsetattr)klassr!rgetr"Zpropr r r res   ) __doc____all__Zxml.domr strrlistrtuplerrr r r r s & __pycache__/minidom.cpython-36.opt-1.pyc000064400000154702147204745200014013 0ustar003 \@sdZddlZddlZddlmZmZmZmZddlTddl m Z m Z ej j jej j jfZGdddej j Z ee dd d ee d d d ee d dd ddZddZddZddZddZGddde ZGddde Zeeddd eed dd eed d!d Gd"d#d#eZeed$d%d eZGd&d'd'eZeddZGd(d)d)e Zeed*d+d eed d,d d-d.ZGd/d0d0Z Gd1d2d2e e Z!Gd3d4d4e e Z"ee"d$d5d Gd6d7d7e"Z#ee#d8d9d ee#d:d;d dd?Z%Gd@dAdAe"Z&GdBdCdCe#Z'GdDdEdEeZ(ee(d$dFd GdGdHdHZ)GdIdJdJe)e e Z*GdKdLdLe)e Z+GdMdNdNe)e e Z,GdOdPdPe Z-GdQdRdReZ.dSdTZ/GdUdVdVe e Z0ee0dWdXd dYdZZ1d[d\Z2d]d^Z3ded_d`Z4dfdadbZ5dgdcddZ6dS)hacSimple implementation of the Level 1 DOM. Namespaces and other minor Level 2 features are also supported. parse("foo.xml") parseString("") Todo: ===== * convenience methods for getting elements and text. * more testing * bring some of the writer and linearizer code into conformance with this interface * SAX 2 namespaces N)EMPTY_NAMESPACE EMPTY_PREFIXXMLNS_NAMESPACEdomreg)*)DOMImplementationLS DocumentLSc@seZdZdZdZdZdZdZeZ ddZ d2ddZ d3dd Z d d Z d d ZddZddZddZddZddZddZddZddZddZd d!Zd"d#Zd$d%Zd&d'Zd(d)Zd*d+Zd,d-Zd.d/Zd0d1Z dS)4NodeNcCsdS)NT)selfr r '/usr/lib64/python3.6/xml/dom/minidom.py__bool__+sz Node.__bool__cCs|jdd|S)N) toprettyxml)r encodingr r r toxml.sz Node.toxml  cCsx|dkrtj}ntjtj|ddd}|jtjkrH|j|d|||n|j|d|||dkrh|jS|j jSdS)Nxmlcharrefreplacer)rerrorsnewliner) ioStringIO TextIOWrapperBytesIOnodeTyper DOCUMENT_NODEwritexmlgetvaluedetach)r indentnewlrwriterr r r r1s   zNode.toprettyxmlcCs t|jS)N)bool childNodes)r r r r hasChildNodesCszNode.hasChildNodescCs|jS)N)r$)r r r r _get_childNodesFszNode._get_childNodescCs|jr|jdSdS)Nr)r$)r r r r _get_firstChildIszNode._get_firstChildcCs|jr|jdSdS)N)r$)r r r r _get_lastChildMszNode._get_lastChildc Cs|j|jkr0xt|jD]}|j||qW|S|j|jkrXtjjdt |t |f|j dk rn|j j ||dkr|j |ny|jj |}Wntk rtjjYnX|jtkrt||jj||||_||_|r|j|d}||_||_nd|_||_ |S)Nz%s cannot be child of %sr()rDOCUMENT_FRAGMENT_NODEtupler$ insertBefore_child_node_typesxmldomHierarchyRequestErrrepr parentNode removeChild appendChildindex ValueError NotFoundErr_nodeTypes_with_children_clear_id_cacheinsert nextSiblingpreviousSibling)r newChildrefChildcr6noder r r r-Qs6      zNode.insertBeforecCs|j|jkr.xt|jD]}|j|qW|S|j|jkrXtjjdt |t |fn|jt krjt ||j dk r|j j |t||d|_|S)Nz%s cannot be child of %s)rr+r,r$r5r.r/r0r1r2r9r:r3r4 _append_childr<)r rAr@r r r r5qs      zNode.appendChildc Cs|j|jkr(|j}|j||j||S|j|jkrPtjjdt |t |f||kr\dS|j dk rr|j j|y|j j |}Wnt k rtjjYnX||j |<||_ d|_ |jtks|jtkrt||j|_|j|_d|_d|_|jr||j_|jr||j_|S)Nz%s cannot be child of %s)rr+r<r4r-r.r/r0r1r2r3r$r6r7r8r9r:r=)r r>oldChildr?r6r r r replaceChilds<         zNode.replaceChildc Csy|jj|Wntk r.tjjYnX|jdk rD|j|j_|jdk rX|j|j_d|_|_|jt krvt |d|_ |S)N) r$remover7r/r0r8r<r=rr9r:r3)r rCr r r r4s      zNode.removeChildcCsg}x|jD]}|jtjkr|jsL|r2|j|d_|jrB|j|j_|jq|r|dj|jkr|d}|j|j|_|j|_|jr||j_|jq|j|q |j||jtj kr |j q W||jdd<dS)Nr(r)r)r)) r$rr TEXT_NODEdatar<r=unlinkappend ELEMENT_NODE normalize)r LchildrAr r r rKs*          zNode.normalizecCst|||jp|S)N) _clone_node ownerDocument)r deepr r r cloneNodeszNode.cloneNodecCs|jjj||S)N)rOimplementation hasFeature)r featureversionr r r isSupportedszNode.isSupportedcCsdS)Nr )r r r r _get_localNameszNode._get_localNamecCs||kS)Nr )r otherr r r isSameNodeszNode.isSameNodecCs|j|dr|SdSdS)N)rV)r rTr r r getInterfaces zNode.getInterfacec Cs,y|j|dSttfk r&dSXdS)Nr) _user_dataAttributeErrorKeyError)r keyr r r getUserDataszNode.getUserDatac Csnd}y |j}Wntk r,i}||_YnX||krB||d}|dkr^d}|dk rj||=n ||f||<|S)Nr)r[r\)r r^rGhandlerolddr r r setUserDatas    zNode.setUserDatacCsHt|drDx8t|jjD]&\}\}}|dk r|j|||||qWdS)Nr[)hasattrlistr[itemsZhandle)r operationsrcdstr^rGr`r r r _call_user_data_handlers zNode._call_user_data_handlercCsBd|_|_|jr2x|jD] }|jqWt|_d|_d|_dS)N)r3rOr$rHNodeListr=r<)r rMr r r rHs   z Node.unlinkcCs|S)Nr )r r r r __enter__szNode.__enter__cCs |jdS)N)rH)r ZetZevtbr r r __exit__sz Node.__exit__)N)rrN)!__name__ __module__ __qualname__ namespaceURIr3rOr<r=rprefixr rrr%r&r'r*r-r5rDr4rKrQrVrWrYrZr_rcrjrHrlrnr r r r r "s:      r firstChildzFirst child node, or None.)doc lastChildzLast child node, or None. localNamez"Namespace-local name of this node.cCs2|j}|r|d}||_||_|j|||_dS)Nr(r))r$r=r<rIr3)r rAr$Zlastr r r rBs rBcCs(x"|dk r"|jtjkrdS|j}qWdS)NTF)rr rr3)rAr r r _in_document&s    rxcCs6|r2|jddjddjddjdd}|j|d S) zWrites datachars to writer.&z&z>N)replacewrite)r"rGr r r _write_data.srcCsHxB|jD]8}|jtjkr4|dks*|j|kr4|j|t|||qW|S)Nr)r$rr rJtagNamerI_get_elements_by_tagName_helper)parentnamercrAr r r r5s    rcCs\xV|jD]L}|jtjkr|dks*|j|krF|dks<|j|krF|j|t||||qW|S)Nr)r$rr rJrwrrrI"_get_elements_by_tagName_ns_helper)rZnsURIrwrrAr r r r=s   rc@sJeZdZejZdZdZdZdZ ej ej ej ej ejejejfZddZdS)DocumentFragmentz#document-fragmentNcCs t|_dS)N)rkr$)r r r r __init__TszDocumentFragment.__init__)rorprqr r+rnodeName nodeValue attributesr3rJrFCDATA_SECTION_NODEENTITY_REFERENCE_NODEPROCESSING_INSTRUCTION_NODE COMMENT_NODE NOTATION_NODEr.rr r r r rFsrc@seZdZd#ZejZd Zd Zd Z ej ej fZ e d d fd d Zd dZddZddZddZeeeZZddZddZeeeZZddZddZeeeZddZdd Zd!d"Zd S)$Attr_name_valuerr_prefixr$ _localNamerO ownerElementNFcCs2d|_||_||_||_t|_|jjtdS)N)rrrrrrkr$rIText)r qNamerrrwrsr r r rbs z Attr.__init__c Cs.y|jStk r(|jjdddSXdS)N:r(r))rr\rsplit)r r r r rWoszAttr._get_localNamecCs|jS)N) specified)r r r r _get_specifieduszAttr._get_specifiedcCs|jS)N)r)r r r r _get_namexszAttr._get_namecCs||_|jdk rt|jdS)N)rrr:)r valuer r r _set_name{s zAttr._set_namecCs|jS)N)r)r r r r _get_valueszAttr._get_valuecCs6||_||jd_|jdk r&t|j||jd_dS)Nr)rr$rGrr:)r rr r r _set_values    zAttr._set_valuecCs|jS)N)r)r r r r _get_prefixszAttr._get_prefixcCsd|j}|dkr&|r&|tkr&tjjd||_|dkr<|j}nd||jf}|jrZt|j||_ dS)Nxmlnsz5illegal use of 'xmlns' prefix for the wrong namespacez%s:%s) rrrr/r0 NamespaceErrrrwrr:r)r rsZnsuriZnewNamer r r _set_prefixs  zAttr._set_prefixcCsz|j}|dk rR|j|j=|j|j|jf=|jrRd|_|jd8_|jj d8_ x|j D] }|j qZW|j dd=dS)NFr() r_attrsr_attrsNSrrrw_is_id_magic_id_nodesrO_magic_id_countr$rH)r elemrMr r r rHs   z Attr.unlinkcCsf|jr dS|j}|j}|dks&|dkr*dS|j|}|dkr@dS|jrV|j|j|jS|j|jSdS)NTF) rrOr_get_elem_inforrisIdNSrwisIdr)r rurinfor r r _get_isIds zAttr._get_isIdcCs\|j}|j}|dks|dkr tS|j|}|dkr6tS|jrL|j|j|jS|j|jSdS)N) rOr_no_typerrrgetAttributeTypeNSrwgetAttributeTyper)r rurrr r r _get_schemaTypes zAttr._get_schemaType)rrrrrr$rrOr) rorprq __slots__r ATTRIBUTE_NODErrrrrFrr.rrrWrrrpropertyrrrrrrrrrsrHrrr r r r rXs.   rrz True if this attribute is an ID.z'Namespace-local name of this attribute. schemaTypezSchema type for this attribute.c@seZdZdZd NamedNodeMapaThe attribute list is a transient interface to the underlying dictionaries. Mutations here will change the underlying element's dictionary. Ordering is imposed artificially and does not reflect the order of attributes as found in an input document. rr _ownerElementcCs||_||_||_dS)N)rrr)r attrsZattrsNSrr r r rszNamedNodeMap.__init__cCs t|jS)N)lenr)r r r r _get_lengthszNamedNodeMap._get_lengthc Cs0y|t|jj|Stk r*dSXdS)N)rerkeys IndexError)r r6r r r itemszNamedNodeMap.itemcCs.g}x$|jjD]}|j|j|jfqW|S)N)rvaluesrIrr)r rLrAr r r rfszNamedNodeMap.itemscCs4g}x*|jjD]}|j|j|jf|jfqW|S)N)rrrIrrrwr)r rLrAr r r itemsNSszNamedNodeMap.itemsNScCs"t|tr||jkS||jkSdS)N) isinstancestrrr)r r^r r r __contains__s  zNamedNodeMap.__contains__cCs |jjS)N)rr)r r r r rszNamedNodeMap.keyscCs |jjS)N)rr)r r r r keysNSszNamedNodeMap.keysNScCs |jjS)N)rr)r r r r rszNamedNodeMap.valuesNcCs|jj||S)N)rget)r rrr r r r szNamedNodeMap.getcCs:|jt|ddkrdSt|t|kt|t|kSdS)Nrr)rgetattrid)r rXr r r _cmpszNamedNodeMap._cmpcCs|j|dkS)Nr)r)r rXr r r __eq__szNamedNodeMap.__eq__cCs|j|dkS)Nr)r)r rXr r r __ge__szNamedNodeMap.__ge__cCs|j|dkS)Nr)r)r rXr r r __gt__szNamedNodeMap.__gt__cCs|j|dkS)Nr)r)r rXr r r __le__szNamedNodeMap.__le__cCs|j|dkS)Nr)r)r rXr r r __lt__!szNamedNodeMap.__lt__cCs"t|tr|j|S|j|SdS)N)rr,rr)r attname_or_tupler r r __getitem__$s  zNamedNodeMap.__getitem__c Csvt|trRy|j|}Wn0tk rHt|}|jj|_|j|YnX||_n t|tsdt d|}|j|dS)Nz%value must be a string or Attr object) rrrr]rrrO setNamedItemr TypeError)r attnamerrAr r r __setitem__+s   zNamedNodeMap.__setitem__c Cs$y |j|Stk rdSXdS)N)rr])r rr r r getNamedItem:s zNamedNodeMap.getNamedItemc Cs(y|j||fStk r"dSXdS)N)rr])r rrrwr r r getNamedItemNS@szNamedNodeMap.getNamedItemNScCsX|j|}|dk rJt|j|j|j=|j|j|jf=t|drFd|_ |St j j dS)Nr) rr:rrrrrrrwrdrr/r0r8)r rnr r r removeNamedItemFs    zNamedNodeMap.removeNamedItemcCsZ|j||}|dk rLt|j|j|j|jf=|j|j=t|drHd|_ |St j j dS)Nr) rr:rrrrrwrrrdrr/r0r8)r rrrwrr r r removeNamedItemNSRs    zNamedNodeMap.removeNamedItemNScCstt|ts&tjjdt|t|f|jj|j}|r@|j ||j|j<||j |j |j f<|j |_t|j|S)Nz%s cannot be child of %s)rrr/r0r1r2rrrrHrrrrwrrr:)r rArar r r r^s   zNamedNodeMap.setNamedItemcCs |j|S)N)r)r rAr r r setNamedItemNSkszNamedNodeMap.setNamedItemNScCs||}t|j|jdS)N)r:rrH)r rrAr r r __delitem__ns zNamedNodeMap.__delitem__cCs|j|j|jfS)N)rrr)r r r r __getstate__sszNamedNodeMap.__getstate__cCs|\|_|_|_dS)N)rrr)r stater r r __setstate__vszNamedNodeMap.__setstate__)rrr)N)!rorprq__doc__rrrrrfrrrrrr__len__rrrrrrrrrrrrrrrrrr r r r rs<    rZlengthz$Number of nodes in the NamedNodeMap.c@s0eZdZd ZddZddZddZd d Zd S) TypeInfo namespacercCs||_||_dS)N)rr)r rrr r r rszTypeInfo.__init__cCs2|jrd|jj|j|jfSd|jj|jfSdS)Nz<%s %r (from %r)>z<%s %r>)r __class__ror)r r r r __repr__s  zTypeInfo.__repr__cCs|jS)N)r)r r r r rszTypeInfo._get_namecCs|jS)N)r)r r r r _get_namespaceszTypeInfo._get_namespaceN)rr)rorprqrrrrrr r r r rs rc @s eZdZdDZejZd ZeZ dZ ejej ej ej ejejfZed d fddZddZddZddZddZddZddZddZdd Zd!d"Zd#d$Zd%d&ZeZd'd(Zd)d*Z d+d,Z!e!Z"d-d.Z#d/d0Z$d1d2Z%d3d4Z&d5d6Z'dEd8d9Z(d:d;Z)dd?Z+d@dAZ,dBdCZ-d S)FElementrOr3rrrsrrrr$rrr<r=NrcCsBd|_||_|_||_||_t|_d|_|_d|_ d|_ dS)N) r3rrrsrrrkr$r<r=rr)r rrrrsrwr r r rs  zElement.__init__cCs|jdkri|_i|_dS)N)rr)r r r r _ensure_attributess zElement._ensure_attributesc Cs.y|jStk r(|jjdddSXdS)Nrr(r))rr\rr)r r r r rWszElement._get_localNamecCs|jS)N)r)r r r r _get_tagNameszElement._get_tagNamecCsD|jdk r*xt|jjD] }|jqWd|_d|_tj|dS)N)rrerrHrr )r attrr r r rHs   zElement.unlinkc Cs4|jdkrdSy |j|jStk r.dSXdS)Nr)rrr])r rr r r getAttributes   zElement.getAttributec Cs8|jdkrdSy|j||fjStk r2dSXdS)Nr)rrr])r rrrwr r r getAttributeNSs  zElement.getAttributeNScCsV|j|}|dkr4t|}||_|j|_|j|n||jkrR||_|jrRt|dS)N)getAttributeNoderrrOsetAttributeNoderr:)r rrrr r r setAttributes   zElement.setAttributecCst|\}}|j||}|dkrHt||||}||_|j|_|j|n4||jkrf||_|jrft||j|kr|||_||_ dS)N) _nssplitgetAttributeNodeNSrrrOrrr:rsr)r rr qualifiedNamerrs localnamerr r r setAttributeNSs     zElement.setAttributeNScCs|jdkrdS|jj|S)N)rr)r Zattrnamer r r rs zElement.getAttributeNodecCs|jdkrdS|jj||fS)N)rr)r rrrwr r r rs zElement.getAttributeNodeNScCs|jd|fkrtjjd|j|jj|jd}|dk rD|j||j j|j |j fd}|dk rt||k rt|j|t ||||k r|S||k r|SdS)Nzattribute node already owned) rr/r0ZInuseAttributeErrrrrrremoveAttributeNoderrrrw_set_attribute_node)r rZold1Zold2r r r rs    zElement.setAttributeNodec CsP|jdkrtjjy|j|}Wntk r@tjjYnX|j|dS)N)rr/r0r8rr]r)r rrr r r removeAttributes  zElement.removeAttributec CsT|jdkrtjjy|j||f}Wntk rDtjjYnX|j|dS)N)rr/r0r8r]r)r rrrwrr r r removeAttributeNS%s  zElement.removeAttributeNSc Cs^|dkrtjjy|j|jWntk r@tjjYnXt||j|j|_dS)N) r/r0r8rrr]r:rHrO)r rAr r r r.s zElement.removeAttributeNodecCs|jdkrdS||jkS)NF)r)r rr r r hasAttribute=s zElement.hasAttributecCs|jdkrdS||f|jkS)NF)r)r rrrwr r r hasAttributeNSBs zElement.hasAttributeNScCst||tS)N)rrk)r rr r r getElementsByTagNameGszElement.getElementsByTagNamecCst|||tS)N)rrk)r rrrwr r r getElementsByTagNameNSJszElement.getElementsByTagNameNScCsd|jt|fS)Nz)rr)r r r r rNszElement.__repr__rc Cs|j|d|j|j}t|j}x4|D],}|jd|t|||j|jdq.W|jr|jdt|jdkr|jdj t j kr|jdj |dddn8|j|x"|jD]}|j |||||qW|j||jd|j|fn|jd |dS) Nrzz %s="r{r|r(rrz%sz/>%s) r~r_get_attributessortedrrrr$rrr rFr) r r"r addindentr!rZa_namesZa_namerAr r r rQs$      zElement.writexmlcCs|jt|j|j|S)N)rrrr)r r r r rlszElement._get_attributescCs|jr dSdSdS)NTF)r)r r r r hasAttributespszElement.hasAttributescCs|j|}|j|dS)N)rsetIdAttributeNode)r ridAttrr r r setIdAttributexs zElement.setIdAttributecCs|j||}|j|dS)N)rr)r rrrwrr r r setIdAttributeNS|s zElement.setIdAttributeNScCsl|dks|j|j r tjjt|dk r6tjj|jshd|_|jd7_|j j d7_ t |dS)NTr() rYrr/r0r8_get_containing_entrefNoModificationAllowedErrrrrOrr:)r rr r r rs   zElement.setIdAttributeNode) rOr3rrrsrrrr$rrr<r=)rrr).rorprqrr rJrrrrrrrrFrrr.rrrrWrrHrrrrrrrZsetAttributeNodeNSrrrZremoveAttributeNodeNSrrrrrrrrrrrr r r r rsT      rrz*NamedNodeMap of attributes on the element.z%Namespace-local name of this element.cCs8t||j||j|j<||j|j|jf<||_dS)N)r:rrrrrrrwr)elementrr r r rs  rc@sfeZdZdZfZdZeZdZdZ ddZ ddZ ddZ d d Z d d Zd dZddZddZdS) ChildlesszMixin that makes childless-ness easy to implement and avoids the complexity of the Node methods that deal with children. NcCsdS)Nr )r r r r r'szChildless._get_firstChildcCsdS)Nr )r r r r r*szChildless._get_lastChildcCstjj|jddS)Nz nodes cannot have children)r/r0r1r)r rAr r r r5szChildless.appendChildcCsdS)NFr )r r r r r%szChildless.hasChildNodescCstjj|jddS)Nz nodes do not have children)r/r0r1r)r r>r?r r r r-szChildless.insertBeforecCstjj|jddS)Nz nodes do not have children)r/r0r8r)r rCr r r r4szChildless.removeChildcCsdS)Nr )r r r r rKszChildless.normalizecCstjj|jddS)Nz nodes do not have children)r/r0r1r)r r>rCr r r rDszChildless.replaceChild)rorprqrrrZ EmptyNodeListr$rtrvr'r*r5r%r-r4rKrDr r r r rsrc@s\eZdZejZdZddZddZddZ e ee Z d d Z d d Z e e e ZdddZdS)ProcessingInstructiontargetrGcCs||_||_dS)N)r rG)r r rGr r r rszProcessingInstruction.__init__cCs|jS)N)rG)r r r r _get_nodeValuesz$ProcessingInstruction._get_nodeValuecCs ||_dS)N)rG)r rr r r _set_nodeValuesz$ProcessingInstruction._set_nodeValuecCs|jS)N)r )r r r r _get_nodeNamesz#ProcessingInstruction._get_nodeNamecCs ||_dS)N)r )r rr r r _set_nodeNamesz#ProcessingInstruction._set_nodeNamercCs|jd||j|j|fdS)Nz %s%s)r~r rG)r r"r rr!r r r rszProcessingInstruction.writexmlN)r rG)rrr)rorprqr rrrrr r rrr r rrr r r r rs  rc@sreZdZdZddZdd ZeZd d Zd d Ze eeZ Z ddZ ddZ ddZddZddZddZdS) CharacterData_datarOr3r=r<cCs,d|_|_d|_|_d|_tj|dS)Nr)rOr3r=r<rr r)r r r r rs  zCharacterData.__init__cCs t|jS)N)rrG)r r r r rszCharacterData._get_lengthcCs|jS)N)r)r r r r _get_dataszCharacterData._get_datacCs ||_dS)N)r)r rGr r r _set_dataszCharacterData._set_datacCs6|j}t|dkrd}nd}d|jj|dd|fS)N z...rzr)rGrrro)r rGZ dotdotdotr r r rs  zCharacterData.__repr__cCsT|dkrtjjd|t|jkr.tjjd|dkrBtjjd|j|||S)Nrzoffset cannot be negativez#offset cannot be beyond end of datazcount cannot be negative)r/r0 IndexSizeErrrrG)r offsetcountr r r substringDatas   zCharacterData.substringDatacCs|j||_dS)N)rG)r argr r r appendDataszCharacterData.appendDatacCsZ|dkrtjjd|t|jkr.tjjd|rVd|jd|||j|df|_dS)Nrzoffset cannot be negativez#offset cannot be beyond end of dataz%s%s%s)r/r0rrrG)r rrr r r insertDatas  zCharacterData.insertDatacCsl|dkrtjjd|t|jkr.tjjd|dkrBtjjd|rh|jd||j||d|_dS)Nrzoffset cannot be negativez#offset cannot be beyond end of datazcount cannot be negative)r/r0rrrG)r rrr r r deleteDatas   zCharacterData.deleteDatacCsr|dkrtjjd|t|jkr.tjjd|dkrBtjjd|rnd|jd|||j||df|_dS)Nrzoffset cannot be negativez#offset cannot be beyond end of datazcount cannot be negativez%s%s%s)r/r0rrrG)r rrrr r r replaceDatas   zCharacterData.replaceDataN)rrOr3r=r<)rorprqrrrrrrrrGrrrrrrrr r r r rs    rzLength of the string data.c@sHeZdZfZejZdZdZddZ dddZ dd Z d d Z d d Z dS)rz#textNcCs|dks|t|jkr"tjjd|j}|j|d|_|j|_|j}|jr~||jj kr~|dkrp|jj |n|jj |||jd||_|S)Nrzillegal offset value) rrGr/r0rrrOr<r3r$r5r-)r rZnewTextnextr r r splitText0s zText.splitTextrcCst|d||j|fdS)Nz%s%s%s)rrG)r r"r rr!r r r r?sz Text.writexmlcCs|jg}|j}x6|dk rD|jtjtjfkr@|jd|j|j}qPqW|j}x4|dk r|jtjtjfkr||j|j|j}qNPqNWdj |S)Nrr) rGr=rr rFrr;r<rIjoin)r rLrr r r _get_wholeTextDs   zText._get_wholeTextcCs|j}|j}x6|dk rB|jtjtjfkr>|j}|j||}qPqW|j}|sX|j|x6|dk r|jtjtjfkr|j}|j||}qZPqZW|r||_|SdSdS)N) r3r=rr rFrr4r<rG)r Zcontentrrrr r r replaceWholeTextVs*     zText.replaceWholeTextcCsF|jjrdSt|}|dkr"dS|jj|}|dkr:dS|jSdS)NF)rGstrip_get_containing_elementrOrisElementContent)r rrr r r !_get_isWhitespaceInElementContentrs  z&Text._get_isWhitespaceInElementContent)rrr)rorprqrr rFrrrrrrr r$r r r r r)s rZisWhitespaceInElementContentzKTrue iff this text node contains only whitespace and is in element content.Z wholeTextz.The text of all logically-adjacent text nodes.cCs.|j}x"|dk r(|jtjkr |S|j}qWdS)N)r3rr rJ)rAr@r r r r"s    r"cCs.|j}x"|dk r(|jtjkr |S|j}qWdS)N)r3rr r)rAr@r r r rs    rc@s(eZdZejZdZddZdddZdS) Commentz#commentcCstj|||_dS)N)rrr)r rGr r r rs zComment.__init__rcCs,d|jkrtd|jd||j|fdS)Nz--z%'--' is not allowed in a comment nodez %s%s)rGr7r~)r r"r rr!r r r rs zComment.writexmlN)rrr) rorprqr rrrrrr r r r r%sr%c@s$eZdZfZejZdZdddZdS) CDATASectionz#cdata-sectionrcCs,|jjddkrtd|jd|jdS)Nz]]>rz$']]>' not allowed in a CDATA sectionz)rGfindr7r~)r r"r rr!r r r rszCDATASection.writexmlN)rrr) rorprqrr rrrrr r r r r&sr&c@s|eZdZdZffddZddZddZdd Zd d Zd d Z ddZ ddZ ddZ ddZ ddZddZddZdS)ReadOnlySequentialNamedNodeMap_seqcCs ||_dS)N)r))r seqr r r rsz'ReadOnlySequentialNamedNodeMap.__init__cCs t|jS)N)rr))r r r r rsz&ReadOnlySequentialNamedNodeMap.__len__cCs t|jS)N)rr))r r r r rsz*ReadOnlySequentialNamedNodeMap._get_lengthcCs"x|jD]}|j|kr|SqWdS)N)r)r)r rrr r r rs  z+ReadOnlySequentialNamedNodeMap.getNamedItemcCs,x&|jD]}|j|kr|j|kr|SqWdS)N)r)rrrw)r rrrwrr r r rs z-ReadOnlySequentialNamedNodeMap.getNamedItemNScCs4t|tr|j|}n |j|}|dkr0t||S)N)rr,rrr])r Z name_or_tuplerAr r r rs    z*ReadOnlySequentialNamedNodeMap.__getitem__c Cs0|dkr dSy |j|Stk r*dSXdS)Nr)r)r)r r6r r r rs  z#ReadOnlySequentialNamedNodeMap.itemcCstjjddS)Nz"NamedNodeMap instance is read-only)r/r0r)r rr r r rsz.ReadOnlySequentialNamedNodeMap.removeNamedItemcCstjjddS)Nz"NamedNodeMap instance is read-only)r/r0r)r rrrwr r r rsz0ReadOnlySequentialNamedNodeMap.removeNamedItemNScCstjjddS)Nz"NamedNodeMap instance is read-only)r/r0r)r rAr r r rsz+ReadOnlySequentialNamedNodeMap.setNamedItemcCstjjddS)Nz"NamedNodeMap instance is read-only)r/r0r)r rAr r r rsz-ReadOnlySequentialNamedNodeMap.setNamedItemNScCs|jgS)N)r))r r r r rsz+ReadOnlySequentialNamedNodeMap.__getstate__cCs|d|_dS)Nr)r))r rr r r rsz+ReadOnlySequentialNamedNodeMap.__setstate__N)r))rorprqrrrrrrrrrrrrrrr r r r r(s  r(z&Number of entries in the NamedNodeMap.c@s,eZdZdZd ZddZddZdd Zd S) Identifiedz@Mix-in class that supports the publicId and systemId attributes.publicIdsystemIdcCs||_||_dS)N)r,r-)r r,r-r r r _identified_mixin_initsz!Identified._identified_mixin_initcCs|jS)N)r,)r r r r _get_publicIdszIdentified._get_publicIdcCs|jS)N)r-)r r r r _get_systemIdszIdentified._get_systemIdN)r,r-)rorprqrrr.r/r0r r r r r+s r+c@sHeZdZejZdZdZdZdZ dZ ddZ ddZ ddZ d d d ZdS) DocumentTypeNcCs2t|_t|_|r&t|\}}||_|j|_dS)N)r(entities notationsrrr)r rrsrr r r r s  zDocumentType.__init__cCs|jS)N)internalSubset)r r r r _get_internalSubsetsz DocumentType._get_internalSubsetcCs|jdkrtd}|j|_|j|_tjjj}|rg|j_ g|j _ x>|j j D]2}t |j|j |j }|j j j||j|||qJWxZ|jj D]N}t|j|j |j |j}|j|_|j|_|j|_|jj j||j|||qW|j||||SdSdS)N)rOr1rrr/r0UserDataHandler NODE_CLONEDr2r)r3Notationr,r-rIrjEntity notationNameactualEncodingrrU)r rPclonergrnotationeentityr r r rQs.  zDocumentType.cloneNodercCs|jd|j|j|jr8|jd||j||jfn|jrR|jd||jf|jdk r||jd|j|j|jd|jd|dS)Nz r r r r5UszEntity.appendChildcCstjjddS)Nz+cannot insert children below an entity node)r/r0r1)r r>r?r r r r-YszEntity.insertBeforecCstjjddS)Nz*cannot remove children from an entity node)r/r0r1)r rCr r r r4]szEntity.removeChildcCstjjddS)Nz)cannot replace children of an entity node)r/r0r1)r r>rCr r r rDaszEntity.replaceChild)rorprqrr Z ENTITY_NODErrr;rrUrrBrCrDr5r-r4rDr r r r r9=sr9c@seZdZejZdZddZdS)r8NcCs||_|j||dS)N)rr.)r rr,r-r r r riszNotation.__init__)rorprqr rrrrr r r r r8esr8c @sHeZdZddddddddgZdd Zd d Zd d ZddZddZdS)DOMImplementationcore1.02.0Nr/ls-load3.0cCs|dkr d}|j|f|jkS)Nr)lower _features)r rTrUr r r rSyszDOMImplementation.hasFeaturec Cs|r|jdk rtjjd|j}|dko8|dko8|dk }| rR|rRtjjd|rt|\}}|dkr~|dkr~tjjd|r| rtjjd|j||}|r|j ||j ||r||_|_ ||_ ||_ |S)Nz(doctype object owned by another DOM treezElement with no namer/z$http://www.w3.org/XML/1998/namespacezillegal use of 'xml' prefixz(illegal use of prefix without namespaces) r3r/r0WrongDocumentErr_create_documentZInvalidCharacterErrrrcreateElementNSr5rOdoctyperR) r rrrrPruZadd_root_elementrsrrr r r createDocument~s4         z DOMImplementation.createDocumentcCst|}||_||_|S)N)r1r,r-)r rr,r-rPr r r createDocumentTypesz$DOMImplementation.createDocumentTypecCs|j|dr|SdSdS)N)rS)r rTr r r rZs zDOMImplementation.getInterfacecCstS)N)Document)r r r r rNsz"DOMImplementation._create_document)rFrG)rFrH)rFN)r/rG)r/rH)r/N)rIrJ)rIN) rorprqrLrSrQrRrZrNr r r r rEns-rEc@s\eZdZdZdZddZddZddZd d Zd d Z d dZ ddZ ddZ ddZ dS) ElementInfozObject that represents content-model information for an element. This implementation is not expected to be used in practice; DOM builders should provide implementations which do the right thing using information available to it. rcCs ||_dS)N)r)r rr r r rszElementInfo.__init__cCstS)N)r)r anamer r r rszElementInfo.getAttributeTypecCstS)N)r)r rrrwr r r rszElementInfo.getAttributeTypeNScCsdS)NFr )r r r r r#szElementInfo.isElementContentcCsdS)zQReturns true iff this element is declared to have an EMPTY content model.Fr )r r r r isEmptyszElementInfo.isEmptycCsdS)z7Returns true iff the named attribute is a DTD-style ID.Fr )r rUr r r rszElementInfo.isIdcCsdS)z|jtjkr|jjd|_nt|r:|jjjd|j_dS)N)rr r _id_cacheclear_id_search_stackrxrO)rAr r r r:s    r:c@sreZdZdMZejejejejfZ e Z ej Z dZdZdZdZdZZdZdZdZdZdZdZdZd Zd d Zd d ZddZddZddZ ddZ!ddZ"ddZ#ddZ$ddZ%ddZ&d d!Z'd"d#Z(d$d%Z)d&d'Z*d(d)Z+d*d+Z,d,d-Z-d.d/Z.d0d1Z/d2d3Z0d4d5Z1d6d7Z2d8d9Z3d:d;Z4dd?Z6d@dAZ7dBdCZ8dDdEZ9dFdGZ:dNdIdJZ;dKdLZ|jj||jtj kr^|j r^tjjdtj ||S)Nz%s cannot be child of %sz two document elements disallowed) rr.r/r0r1r2r3r4r rJ_get_documentElementr5)r rAr r r r52s    zDocument.appendChildc CsVy|jj|Wntk r.tjjYnXd|_|_d|_|j |krRd|_ |S)N) r$rEr7r/r0r8r<r=r3documentElement)r rCr r r r4Bs  zDocument.removeChildcCs$x|jD]}|jtjkr|SqWdS)N)r$rr rJ)r rAr r r rdNs  zDocument._get_documentElementcCs(|jdk r|jjd|_tj|dS)N)rPrHr )r r r r rHSs  zDocument.unlinkcCs|sdS|jjddd}|j|_|j|_|j|_xL|jD]B}t|||}|jj||jt j krbn|jt j krt||_ ||_ q8W|jtjjj|||S)N)rRrQrr`rUr$rNrIrr rrArPr3rjr/r0r6r7)r rPr<rZ childcloner r r rQYs"       zDocument.cloneNodecCst}||_|S)N)rrO)r rbr r r createDocumentFragmentnszDocument.createDocumentFragmentcCst|}||_|S)N)rrO)r rr>r r r createElementsszDocument.createElementcCs(t|tstdt}||_||_|S)Nznode contents must be a string)rrrrrGrO)r rGtr r r createTextNodexs  zDocument.createTextNodecCs(t|tstdt}||_||_|S)Nznode contents must be a string)rrrr&rGrO)r rGr@r r r createCDATASections  zDocument.createCDATASectioncCst|}||_|S)N)r%rO)r rGr@r r r createCommentszDocument.createCommentcCst||}||_|S)N)rrO)r r rGpr r r createProcessingInstructions z$Document.createProcessingInstructioncCst|}||_d|_|S)Nr)rrOr)r rar r r createAttributeszDocument.createAttributecCs"t|\}}t|||}||_|S)N)rrrO)r rrrrsrwr>r r r rOs  zDocument.createElementNScCs*t|\}}t||||}||_d|_|S)Nr)rrrOr)r rrrrsrwrnr r r createAttributeNSs  zDocument.createAttributeNScCst||||}||_|S)N)r9rO)r rr,r-r:r>r r r _create_entityszDocument._create_entitycCst|||}||_|S)N)r8rO)r rr,r-rr r r _create_notations zDocument._create_notationcCs||jkr|j|S|jp|js$dS|j}|dkrB|jg}||_n|sJdSd}x>|r|j}|jdd|jD|j|}|r@x|j j D]}|j r|j |j |j r||j|j<|j|kr|}n|jsPq|j|jr ||j|j<|j|kr|}n |js:Pq|jr||j|j<|j|kr.|}q|jdkrPqWnB|jrx8|j j D]*}|jrT||j|j<|j|krT|}qTW|dk rRPqRW|S)NcSsg|]}|jtkr|qSr )rr9).0rMr r r sz+Document.getElementById..r()rWrZrrYrepopextendr$rrrrrrrwrrrrr)r rstackresultrArrr r r getElementByIdsZ               zDocument.getElementByIdcCst||tS)N)rrk)r rr r r rszDocument.getElementsByTagNamecCst|||tS)N)rrk)r rrrwr r r rszDocument.getElementsByTagNameNScCs|jj||S)N)rRrS)r rTrUr r r rVszDocument.isSupportedcCs>|jtjkrtjjdn|jtjkr2tjjdt|||S)Nzcannot import document nodesz!cannot import document type nodes)rr rr/r0NotSupportedErrrArN)r rArPr r r importNodes    zDocument.importNodercCsN|dkr|jd|n|jd||fx|jD]}|j||||q2WdS)Nzz%%s)r~r$r)r r"r rr!rrAr r r rs   zDocument.writexmlcCsJ|j|k r tjjd||jf|jtjtjfkr>tjjd|t krd|kr|j dd\}}|dkr|tjj krtjj dq|dkr|tjj kr|jtjkrtjj dd}|}nd}d}|jtjkr|j }|dk r|j}|j|nd}||_||_||_||_|jtjkr||_n*||_|dk rF|j||rF|j||S)Nz?cannot rename nodes from other documents; expected %s, found %sz8renameNode() only applies to element and attribute nodesrr(rzillegal use of 'xmlns' prefixz$illegal use of the 'xmlns' attribute)rOr/r0rMrr rJrrzrrrrrrrrsrrrrrrrr)r rrrrrsrwrZis_idr r r renameNodesR         zDocument.renameNode)rZrPrYr$rW)rrrN)=rorprqrr rJrrrAr.rErRrrrrrr3r=r<r;rr`rUrbr^r\rrrrBr[r]rCr_rarcrDr5r4rdrHrQrfrgrirjrkrmrorOrprqrrryrrrVr{rr|r r r r rSsh    : rSrez#Top-level element of this document.c Cs|jj|rtjjj}n tjjj}|jtj kr|j |j |j }x>|j jD]0}|j|j |j |j|j|j |j}|j|_qJW|rx$|jD]}t|||}|j|qWn|jtjkr|j}|rx$|jD]}t|||}|j|qWn|jtjkr |j|j}n|jtjkr*|j|j}n|jtjkrL|j|j |j}nr|jtj!krj|j"|j}nT|jtj#kr|j$|j |j }d|_|j|_n$|jtj%krtjjj}|j&j'|j(|j)|j*}||_|rg|j+_,g|j-_,xR|j-j,D]F} t.| j | j)| j*} || _|j-j,j/| t0| dr| j1|| | qWx|j+j,D]b} t2| j | j)| j*| j3} | j4| _4| j5| _5| j6| _6|| _|j+j,j/| t0| drB| j1|| | qBWntjj7dt8|t0|dr|j1||||S)zo Clone a node and give it the new owner document. Called by Node.cloneNode and Document.importNode TrjzCannot clone node %s)9rOrYr/r0r6r7Z NODE_IMPORTEDrr rJrOrrrrrrrrrwrr$rNr5r+rfrFrirGrrjrrmr rrkrrprArRrRrr,r-r2r)r3r8rIrdrjr9r:r;rrUrzr2) rArPZnewOwnerDocumentrgr<rrnrMr@rr=r>r?r r r rNAs|                rNcCs,|jdd}t|dkr|Sd|dfSdS)Nrr(r)rr)rZfieldsr r r rs  rcCs,|||}|j\}}|j||j|S)N)ZgetEventZ expandNoderX)funcargskwargsZeventsZtoktypeZrootNoder r r _do_pulldom_parses    rcCsJ|dkr$| r$ddlm}|j|Sddlm}t|j|f||dSdS)z3Parse a file into a DOM by filename or file object.Nr) expatbuilder)pulldom)parserbufsize)xml.domrparserr)filerrrrr r r rs     rcCsB|dkrddlm}|j|Sddlm}t|j|fd|iSdS)z&Parse a file into a DOM from a string.Nr)r)rr)rr parseStringrr)stringrrrr r r rs     rcCsB|rs v  y$ w )GU  ><( O*PR __pycache__/minidom.cpython-36.opt-2.pyc000064400000151634147204745200014015 0ustar003 \@sddlZddlZddlmZmZmZmZddlTddlm Z m Z ej j j ej j jfZGdddej j Z ee ddd ee d d d ee d d d ddZddZddZddZddZGddde ZGddde Zeeddd eed dd eedd d Gd!d"d"eZeed#d$d eZGd%d&d&eZeddZGd'd(d(e Zeed)d*d eed d+d d,d-ZGd.d/d/ZGd0d1d1ee Z Gd2d3d3ee Z!ee!d#d4d Gd5d6d6e!Z"ee"d7d8d ee"d9d:d d;d<Z#d=d>Z$Gd?d@d@e!Z%GdAdBdBe"Z&GdCdDdDeZ'ee'd#dEd GdFdGdGZ(GdHdIdIe(ee Z)GdJdKdKe(e Z*GdLdMdMe(ee Z+GdNdOdOe Z,GdPdQdQeZ-dRdSZ.GdTdUdUe e Z/ee/dVdWd dXdYZ0dZd[Z1d\d]Z2ddd^d_Z3ded`daZ4dfdbdcZ5dS)gN)EMPTY_NAMESPACE EMPTY_PREFIXXMLNS_NAMESPACEdomreg)*)DOMImplementationLS DocumentLSc@seZdZdZdZdZdZdZeZ ddZ d2ddZ d3dd Z d d Z d d ZddZddZddZddZddZddZddZddZddZd d!Zd"d#Zd$d%Zd&d'Zd(d)Zd*d+Zd,d-Zd.d/Zd0d1Z dS)4NodeNcCsdS)NT)selfr r '/usr/lib64/python3.6/xml/dom/minidom.py__bool__+sz Node.__bool__cCs|jdd|S)N) toprettyxml)r encodingr r r toxml.sz Node.toxml  cCsx|dkrtj}ntjtj|ddd}|jtjkrH|j|d|||n|j|d|||dkrh|jS|j jSdS)Nxmlcharrefreplacer)rerrorsnewliner) ioStringIO TextIOWrapperBytesIOnodeTyper DOCUMENT_NODEwritexmlgetvaluedetach)r indentnewlrwriterr r r r1s   zNode.toprettyxmlcCs t|jS)N)bool childNodes)r r r r hasChildNodesCszNode.hasChildNodescCs|jS)N)r$)r r r r _get_childNodesFszNode._get_childNodescCs|jr|jdSdS)Nr)r$)r r r r _get_firstChildIszNode._get_firstChildcCs|jr|jdSdS)N)r$)r r r r _get_lastChildMszNode._get_lastChildc Cs|j|jkr0xt|jD]}|j||qW|S|j|jkrXtjjdt |t |f|j dk rn|j j ||dkr|j |ny|jj |}Wntk rtjjYnX|jtkrt||jj||||_||_|r|j|d}||_||_nd|_||_ |S)Nz%s cannot be child of %sr()rDOCUMENT_FRAGMENT_NODEtupler$ insertBefore_child_node_typesxmldomHierarchyRequestErrrepr parentNode removeChild appendChildindex ValueError NotFoundErr_nodeTypes_with_children_clear_id_cacheinsert nextSiblingpreviousSibling)r newChildrefChildcr6noder r r r-Qs6      zNode.insertBeforecCs|j|jkr.xt|jD]}|j|qW|S|j|jkrXtjjdt |t |fn|jt krjt ||j dk r|j j |t||d|_|S)Nz%s cannot be child of %s)rr+r,r$r5r.r/r0r1r2r9r:r3r4 _append_childr<)r rAr@r r r r5qs      zNode.appendChildc Cs|j|jkr(|j}|j||j||S|j|jkrPtjjdt |t |f||kr\dS|j dk rr|j j|y|j j |}Wnt k rtjjYnX||j |<||_ d|_ |jtks|jtkrt||j|_|j|_d|_d|_|jr||j_|jr||j_|S)Nz%s cannot be child of %s)rr+r<r4r-r.r/r0r1r2r3r$r6r7r8r9r:r=)r r>oldChildr?r6r r r replaceChilds<         zNode.replaceChildc Csy|jj|Wntk r.tjjYnX|jdk rD|j|j_|jdk rX|j|j_d|_|_|jt krvt |d|_ |S)N) r$remover7r/r0r8r<r=rr9r:r3)r rCr r r r4s      zNode.removeChildcCsg}x|jD]}|jtjkr|jsL|r2|j|d_|jrB|j|j_|jq|r|dj|jkr|d}|j|j|_|j|_|jr||j_|jq|j|q |j||jtj kr |j q W||jdd<dS)Nr(r)r)r)) r$rr TEXT_NODEdatar<r=unlinkappend ELEMENT_NODE normalize)r LchildrAr r r rKs*          zNode.normalizecCst|||jp|S)N) _clone_node ownerDocument)r deepr r r cloneNodeszNode.cloneNodecCs|jjj||S)N)rOimplementation hasFeature)r featureversionr r r isSupportedszNode.isSupportedcCsdS)Nr )r r r r _get_localNameszNode._get_localNamecCs||kS)Nr )r otherr r r isSameNodeszNode.isSameNodecCs|j|dr|SdSdS)N)rV)r rTr r r getInterfaces zNode.getInterfacec Cs,y|j|dSttfk r&dSXdS)Nr) _user_dataAttributeErrorKeyError)r keyr r r getUserDataszNode.getUserDatac Csnd}y |j}Wntk r,i}||_YnX||krB||d}|dkr^d}|dk rj||=n ||f||<|S)Nr)r[r\)r r^rGhandlerolddr r r setUserDatas    zNode.setUserDatacCsHt|drDx8t|jjD]&\}\}}|dk r|j|||||qWdS)Nr[)hasattrlistr[itemsZhandle)r operationsrcdstr^rGr`r r r _call_user_data_handlers zNode._call_user_data_handlercCsBd|_|_|jr2x|jD] }|jqWt|_d|_d|_dS)N)r3rOr$rHNodeListr=r<)r rMr r r rHs   z Node.unlinkcCs|S)Nr )r r r r __enter__szNode.__enter__cCs |jdS)N)rH)r ZetZevtbr r r __exit__sz Node.__exit__)N)rrN)!__name__ __module__ __qualname__ namespaceURIr3rOr<r=rprefixr rrr%r&r'r*r-r5rDr4rKrQrVrWrYrZr_rcrjrHrlrnr r r r r "s:      r firstChildzFirst child node, or None.)doc lastChildzLast child node, or None. localNamez"Namespace-local name of this node.cCs2|j}|r|d}||_||_|j|||_dS)Nr(r))r$r=r<rIr3)r rAr$Zlastr r r rBs rBcCs(x"|dk r"|jtjkrdS|j}qWdS)NTF)rr rr3)rAr r r _in_document&s    rxcCs6|r2|jddjddjddjdd}|j|dS) N&z&z>)replacewrite)r"rGr r r _write_data.srcCsHxB|jD]8}|jtjkr4|dks*|j|kr4|j|t|||qW|S)Nr)r$rr rJtagNamerI_get_elements_by_tagName_helper)parentnamercrAr r r r5s    rcCs\xV|jD]L}|jtjkr|dks*|j|krF|dks<|j|krF|j|t||||qW|S)Nr)r$rr rJrwrrrI"_get_elements_by_tagName_ns_helper)rZnsURIrwrrAr r r r=s   rc@sJeZdZejZdZdZdZdZ ej ej ej ej ejejejfZddZdS)DocumentFragmentz#document-fragmentNcCs t|_dS)N)rkr$)r r r r __init__TszDocumentFragment.__init__)rorprqr r+rnodeName nodeValue attributesr3rJrFCDATA_SECTION_NODEENTITY_REFERENCE_NODEPROCESSING_INSTRUCTION_NODE COMMENT_NODE NOTATION_NODEr.rr r r r rFsrc@seZdZd#ZejZd Zd Zd Z ej ej fZ e d d fd d Zd dZddZddZddZeeeZZddZddZeeeZZddZddZeeeZddZdd Zd!d"Zd S)$Attr_name_valuerr_prefixr$ _localNamerO ownerElementNFcCs2d|_||_||_||_t|_|jjtdS)N)rrrrrrkr$rIText)r qNamerrrwrsr r r rbs z Attr.__init__c Cs.y|jStk r(|jjdddSXdS)N:r(r))rr\rsplit)r r r r rWoszAttr._get_localNamecCs|jS)N) specified)r r r r _get_specifieduszAttr._get_specifiedcCs|jS)N)r)r r r r _get_namexszAttr._get_namecCs||_|jdk rt|jdS)N)rrr:)r valuer r r _set_name{s zAttr._set_namecCs|jS)N)r)r r r r _get_valueszAttr._get_valuecCs6||_||jd_|jdk r&t|j||jd_dS)Nr)rr$rGrr:)r rr r r _set_values    zAttr._set_valuecCs|jS)N)r)r r r r _get_prefixszAttr._get_prefixcCsd|j}|dkr&|r&|tkr&tjjd||_|dkr<|j}nd||jf}|jrZt|j||_ dS)Nxmlnsz5illegal use of 'xmlns' prefix for the wrong namespacez%s:%s) rrrr/r0 NamespaceErrrrwrr:r)r rsZnsuriZnewNamer r r _set_prefixs  zAttr._set_prefixcCsz|j}|dk rR|j|j=|j|j|jf=|jrRd|_|jd8_|jj d8_ x|j D] }|j qZW|j dd=dS)NFr() r_attrsr_attrsNSrrrw_is_id_magic_id_nodesrO_magic_id_countr$rH)r elemrMr r r rHs   z Attr.unlinkcCsf|jr dS|j}|j}|dks&|dkr*dS|j|}|dkr@dS|jrV|j|j|jS|j|jSdS)NTF) rrOr_get_elem_inforrisIdNSrwisIdr)r rurinfor r r _get_isIds zAttr._get_isIdcCs\|j}|j}|dks|dkr tS|j|}|dkr6tS|jrL|j|j|jS|j|jSdS)N) rOr_no_typerrrgetAttributeTypeNSrwgetAttributeTyper)r rurrr r r _get_schemaTypes zAttr._get_schemaType)rrrrrr$rrOr) rorprq __slots__r ATTRIBUTE_NODErrrrrFrr.rrrWrrrpropertyrrrrrrrrrsrHrrr r r r rXs.   rrz True if this attribute is an ID.z'Namespace-local name of this attribute. schemaTypezSchema type for this attribute.c@seZdZd;ZddZddZdd Zd d Zd d ZddZ ddZ ddZ ddZ dz<%s %r>)r __class__ror)r r r r __repr__s  zTypeInfo.__repr__cCs|jS)N)r)r r r r rszTypeInfo._get_namecCs|jS)N)r)r r r r _get_namespaceszTypeInfo._get_namespaceN)rr)rorprqrrrrrr r r r rs rc @s eZdZdDZejZd ZeZ dZ ejej ej ej ejejfZed d fddZddZddZddZddZddZddZddZdd Zd!d"Zd#d$Zd%d&ZeZd'd(Zd)d*Z d+d,Z!e!Z"d-d.Z#d/d0Z$d1d2Z%d3d4Z&d5d6Z'dEd8d9Z(d:d;Z)dd?Z+d@dAZ,dBdCZ-d S)FElementrOr3rrrsrrrr$rrr<r=NrcCsBd|_||_|_||_||_t|_d|_|_d|_ d|_ dS)N) r3rrrsrrrkr$r<r=rr)r rrrrsrwr r r rs  zElement.__init__cCs|jdkri|_i|_dS)N)rr)r r r r _ensure_attributess zElement._ensure_attributesc Cs.y|jStk r(|jjdddSXdS)Nrr(r))rr\rr)r r r r rWszElement._get_localNamecCs|jS)N)r)r r r r _get_tagNameszElement._get_tagNamecCsD|jdk r*xt|jjD] }|jqWd|_d|_tj|dS)N)rrerrHrr )r attrr r r rHs   zElement.unlinkc Cs4|jdkrdSy |j|jStk r.dSXdS)Nr)rrr])r rr r r getAttributes   zElement.getAttributec Cs8|jdkrdSy|j||fjStk r2dSXdS)Nr)rrr])r rrrwr r r getAttributeNSs  zElement.getAttributeNScCsV|j|}|dkr4t|}||_|j|_|j|n||jkrR||_|jrRt|dS)N)getAttributeNoderrrOsetAttributeNoderr:)r rrrr r r setAttributes   zElement.setAttributecCst|\}}|j||}|dkrHt||||}||_|j|_|j|n4||jkrf||_|jrft||j|kr|||_||_ dS)N) _nssplitgetAttributeNodeNSrrrOrrr:rsr)r rr qualifiedNamerrs localnamerr r r setAttributeNSs     zElement.setAttributeNScCs|jdkrdS|jj|S)N)rr)r Zattrnamer r r rs zElement.getAttributeNodecCs|jdkrdS|jj||fS)N)rr)r rrrwr r r rs zElement.getAttributeNodeNScCs|jd|fkrtjjd|j|jj|jd}|dk rD|j||j j|j |j fd}|dk rt||k rt|j|t ||||k r|S||k r|SdS)Nzattribute node already owned) rr/r0ZInuseAttributeErrrrrrremoveAttributeNoderrrrw_set_attribute_node)r rZold1Zold2r r r rs    zElement.setAttributeNodec CsP|jdkrtjjy|j|}Wntk r@tjjYnX|j|dS)N)rr/r0r8rr]r)r rrr r r removeAttributes  zElement.removeAttributec CsT|jdkrtjjy|j||f}Wntk rDtjjYnX|j|dS)N)rr/r0r8r]r)r rrrwrr r r removeAttributeNS%s  zElement.removeAttributeNSc Cs^|dkrtjjy|j|jWntk r@tjjYnXt||j|j|_dS)N) r/r0r8rrr]r:rHrO)r rAr r r r.s zElement.removeAttributeNodecCs|jdkrdS||jkS)NF)r)r rr r r hasAttribute=s zElement.hasAttributecCs|jdkrdS||f|jkS)NF)r)r rrrwr r r hasAttributeNSBs zElement.hasAttributeNScCst||tS)N)rrk)r rr r r getElementsByTagNameGszElement.getElementsByTagNamecCst|||tS)N)rrk)r rrrwr r r getElementsByTagNameNSJszElement.getElementsByTagNameNScCsd|jt|fS)Nz)rr)r r r r rNszElement.__repr__rc Cs|j|d|j|j}t|j}x4|D],}|jd|t|||j|jdq.W|jr|jdt|jdkr|jdj t j kr|jdj |dddn8|j|x"|jD]}|j |||||qW|j||jd|j|fn|jd |dS) Nrzz %s="r{r|r(rrz%sz/>%s) r~r_get_attributessortedrrrr$rrr rFr) r r"r addindentr!rZa_namesZa_namerAr r r rQs$      zElement.writexmlcCs|jt|j|j|S)N)rrrr)r r r r rlszElement._get_attributescCs|jr dSdSdS)NTF)r)r r r r hasAttributespszElement.hasAttributescCs|j|}|j|dS)N)rsetIdAttributeNode)r ridAttrr r r setIdAttributexs zElement.setIdAttributecCs|j||}|j|dS)N)rr)r rrrwrr r r setIdAttributeNS|s zElement.setIdAttributeNScCsl|dks|j|j r tjjt|dk r6tjj|jshd|_|jd7_|j j d7_ t |dS)NTr() rYrr/r0r8_get_containing_entrefNoModificationAllowedErrrrrOrr:)r rr r r rs   zElement.setIdAttributeNode) rOr3rrrsrrrr$rrr<r=)rrr).rorprqrr rJrrrrrrrrFrrr.rrrrWrrHrrrrrrrZsetAttributeNodeNSrrrZremoveAttributeNodeNSrrrrrrrrrrrr r r r rsT      rrz*NamedNodeMap of attributes on the element.z%Namespace-local name of this element.cCs8t||j||j|j<||j|j|jf<||_dS)N)r:rrrrrrrwr)elementrr r r rs  rc@sbeZdZfZdZeZdZdZddZ ddZ ddZ dd Z d d Z d d ZddZddZdS) ChildlessNcCsdS)Nr )r r r r r'szChildless._get_firstChildcCsdS)Nr )r r r r r*szChildless._get_lastChildcCstjj|jddS)Nz nodes cannot have children)r/r0r1r)r rAr r r r5szChildless.appendChildcCsdS)NFr )r r r r r%szChildless.hasChildNodescCstjj|jddS)Nz nodes do not have children)r/r0r1r)r r>r?r r r r-szChildless.insertBeforecCstjj|jddS)Nz nodes do not have children)r/r0r8r)r rCr r r r4szChildless.removeChildcCsdS)Nr )r r r r rKszChildless.normalizecCstjj|jddS)Nz nodes do not have children)r/r0r1r)r r>rCr r r rDszChildless.replaceChild)rorprqrrZ EmptyNodeListr$rtrvr'r*r5r%r-r4rKrDr r r r rsrc@s\eZdZejZdZddZddZddZ e ee Z d d Z d d Z e e e ZdddZdS)ProcessingInstructiontargetrGcCs||_||_dS)N)rrG)r rrGr r r rszProcessingInstruction.__init__cCs|jS)N)rG)r r r r _get_nodeValuesz$ProcessingInstruction._get_nodeValuecCs ||_dS)N)rG)r rr r r _set_nodeValuesz$ProcessingInstruction._set_nodeValuecCs|jS)N)r)r r r r _get_nodeNamesz#ProcessingInstruction._get_nodeNamecCs ||_dS)N)r)r rr r r _set_nodeNamesz#ProcessingInstruction._set_nodeNamercCs|jd||j|j|fdS)Nz %s%s)r~rrG)r r"r rr!r r r rszProcessingInstruction.writexmlN)rrG)rrr)rorprqr rrrrr r rrr r rrr r r r rs  rc@sreZdZdZddZdd ZeZd d Zd d Ze eeZ Z ddZ ddZ ddZddZddZddZdS) CharacterData_datarOr3r=r<cCs,d|_|_d|_|_d|_tj|dS)Nr)rOr3r=r<rr r)r r r r rs  zCharacterData.__init__cCs t|jS)N)rrG)r r r r rszCharacterData._get_lengthcCs|jS)N)r)r r r r _get_dataszCharacterData._get_datacCs ||_dS)N)r)r rGr r r _set_dataszCharacterData._set_datacCs6|j}t|dkrd}nd}d|jj|dd|fS)N z...rzr)rGrrro)r rGZ dotdotdotr r r rs  zCharacterData.__repr__cCsT|dkrtjjd|t|jkr.tjjd|dkrBtjjd|j|||S)Nrzoffset cannot be negativez#offset cannot be beyond end of datazcount cannot be negative)r/r0 IndexSizeErrrrG)r offsetcountr r r substringDatas   zCharacterData.substringDatacCs|j||_dS)N)rG)r argr r r appendDataszCharacterData.appendDatacCsZ|dkrtjjd|t|jkr.tjjd|rVd|jd|||j|df|_dS)Nrzoffset cannot be negativez#offset cannot be beyond end of dataz%s%s%s)r/r0rrrG)r rrr r r insertDatas  zCharacterData.insertDatacCsl|dkrtjjd|t|jkr.tjjd|dkrBtjjd|rh|jd||j||d|_dS)Nrzoffset cannot be negativez#offset cannot be beyond end of datazcount cannot be negative)r/r0rrrG)r rrr r r deleteDatas   zCharacterData.deleteDatacCsr|dkrtjjd|t|jkr.tjjd|dkrBtjjd|rnd|jd|||j||df|_dS)Nrzoffset cannot be negativez#offset cannot be beyond end of datazcount cannot be negativez%s%s%s)r/r0rrrG)r rrrr r r replaceDatas   zCharacterData.replaceDataN)rrOr3r=r<)rorprqrrrrrrrrGrrrrrrrr r r r r s    r zLength of the string data.c@sHeZdZfZejZdZdZddZ dddZ dd Z d d Z d d Z dS)rz#textNcCs|dks|t|jkr"tjjd|j}|j|d|_|j|_|j}|jr~||jj kr~|dkrp|jj |n|jj |||jd||_|S)Nrzillegal offset value) rrGr/r0rrrOr<r3r$r5r-)r rZnewTextnextr r r splitText0s zText.splitTextrcCst|d||j|fdS)Nz%s%s%s)rrG)r r"r rr!r r r r?sz Text.writexmlcCs|jg}|j}x6|dk rD|jtjtjfkr@|jd|j|j}qPqW|j}x4|dk r|jtjtjfkr||j|j|j}qNPqNWdj |S)Nrr) rGr=rr rFrr;r<rIjoin)r rLrr r r _get_wholeTextDs   zText._get_wholeTextcCs|j}|j}x6|dk rB|jtjtjfkr>|j}|j||}qPqW|j}|sX|j|x6|dk r|jtjtjfkr|j}|j||}qZPqZW|r||_|SdSdS)N) r3r=rr rFrr4r<rG)r Zcontentrrrr r r replaceWholeTextVs*     zText.replaceWholeTextcCsF|jjrdSt|}|dkr"dS|jj|}|dkr:dS|jSdS)NF)rGstrip_get_containing_elementrOrisElementContent)r rrr r r !_get_isWhitespaceInElementContentrs  z&Text._get_isWhitespaceInElementContent)rrr)rorprqrr rFrrrrrrrr#r r r r r)s rZisWhitespaceInElementContentzKTrue iff this text node contains only whitespace and is in element content.Z wholeTextz.The text of all logically-adjacent text nodes.cCs.|j}x"|dk r(|jtjkr |S|j}qWdS)N)r3rr rJ)rAr@r r r r!s    r!cCs.|j}x"|dk r(|jtjkr |S|j}qWdS)N)r3rr r)rAr@r r r rs    rc@s(eZdZejZdZddZdddZdS) Commentz#commentcCstj|||_dS)N)r rr)r rGr r r rs zComment.__init__rcCs,d|jkrtd|jd||j|fdS)Nz--z%'--' is not allowed in a comment nodez %s%s)rGr7r~)r r"r rr!r r r rs zComment.writexmlN)rrr) rorprqr rrrrrr r r r r$sr$c@s$eZdZfZejZdZdddZdS) CDATASectionz#cdata-sectionrcCs,|jjddkrtd|jd|jdS)Nz]]>rz$']]>' not allowed in a CDATA sectionz)rGfindr7r~)r r"r rr!r r r rszCDATASection.writexmlN)rrr) rorprqrr rrrrr r r r r%sr%c@s|eZdZdZffddZddZddZdd Zd d Zd d Z ddZ ddZ ddZ ddZ ddZddZddZdS)ReadOnlySequentialNamedNodeMap_seqcCs ||_dS)N)r()r seqr r r rsz'ReadOnlySequentialNamedNodeMap.__init__cCs t|jS)N)rr()r r r r rsz&ReadOnlySequentialNamedNodeMap.__len__cCs t|jS)N)rr()r r r r rsz*ReadOnlySequentialNamedNodeMap._get_lengthcCs"x|jD]}|j|kr|SqWdS)N)r(r)r rrr r r rs  z+ReadOnlySequentialNamedNodeMap.getNamedItemcCs,x&|jD]}|j|kr|j|kr|SqWdS)N)r(rrrw)r rrrwrr r r rs z-ReadOnlySequentialNamedNodeMap.getNamedItemNScCs4t|tr|j|}n |j|}|dkr0t||S)N)rr,rrr])r Z name_or_tuplerAr r r rs    z*ReadOnlySequentialNamedNodeMap.__getitem__c Cs0|dkr dSy |j|Stk r*dSXdS)Nr)r(r)r r6r r r rs  z#ReadOnlySequentialNamedNodeMap.itemcCstjjddS)Nz"NamedNodeMap instance is read-only)r/r0r)r rr r r rsz.ReadOnlySequentialNamedNodeMap.removeNamedItemcCstjjddS)Nz"NamedNodeMap instance is read-only)r/r0r)r rrrwr r r rsz0ReadOnlySequentialNamedNodeMap.removeNamedItemNScCstjjddS)Nz"NamedNodeMap instance is read-only)r/r0r)r rAr r r rsz+ReadOnlySequentialNamedNodeMap.setNamedItemcCstjjddS)Nz"NamedNodeMap instance is read-only)r/r0r)r rAr r r rsz-ReadOnlySequentialNamedNodeMap.setNamedItemNScCs|jgS)N)r()r r r r rsz+ReadOnlySequentialNamedNodeMap.__getstate__cCs|d|_dS)Nr)r()r rr r r rsz+ReadOnlySequentialNamedNodeMap.__setstate__N)r()rorprqrrrrrrrrrrrrrrr r r r r's  r'z&Number of entries in the NamedNodeMap.c@s(eZdZd ZddZddZddZd S) IdentifiedpublicIdsystemIdcCs||_||_dS)N)r+r,)r r+r,r r r _identified_mixin_initsz!Identified._identified_mixin_initcCs|jS)N)r+)r r r r _get_publicIdszIdentified._get_publicIdcCs|jS)N)r,)r r r r _get_systemIdszIdentified._get_systemIdN)r+r,)rorprqrr-r.r/r r r r r*sr*c@sHeZdZejZdZdZdZdZ dZ ddZ ddZ ddZ d d d ZdS) DocumentTypeNcCs2t|_t|_|r&t|\}}||_|j|_dS)N)r'entities notationsrrr)r rrsrr r r r s  zDocumentType.__init__cCs|jS)N)internalSubset)r r r r _get_internalSubsetsz DocumentType._get_internalSubsetcCs|jdkrtd}|j|_|j|_tjjj}|rg|j_ g|j _ x>|j j D]2}t |j|j |j }|j j j||j|||qJWxZ|jj D]N}t|j|j |j |j}|j|_|j|_|j|_|jj j||j|||qW|j||||SdSdS)N)rOr0rrr/r0UserDataHandler NODE_CLONEDr1r(r2Notationr+r,rIrjEntity notationNameactualEncodingrrU)r rPclonergrnotationeentityr r r rQs.  zDocumentType.cloneNodercCs|jd|j|j|jr8|jd||j||jfn|jrR|jd||jf|jdk r||jd|j|j|jd|jd|dS)Nz r r r r5UszEntity.appendChildcCstjjddS)Nz+cannot insert children below an entity node)r/r0r1)r r>r?r r r r-YszEntity.insertBeforecCstjjddS)Nz*cannot remove children from an entity node)r/r0r1)r rCr r r r4]szEntity.removeChildcCstjjddS)Nz)cannot replace children of an entity node)r/r0r1)r r>rCr r r rDaszEntity.replaceChild)rorprqrr Z ENTITY_NODErrr:rrUrrArBrCr5r-r4rDr r r r r8=sr8c@seZdZejZdZddZdS)r7NcCs||_|j||dS)N)rr-)r rr+r,r r r riszNotation.__init__)rorprqr rrrrr r r r r7esr7c @sHeZdZddddddddgZdd Zd d Zd d ZddZddZdS)DOMImplementationcore1.02.0Nr/ls-load3.0cCs|dkr d}|j|f|jkS)Nr)lower _features)r rTrUr r r rSyszDOMImplementation.hasFeaturec Cs|r|jdk rtjjd|j}|dko8|dko8|dk }| rR|rRtjjd|rt|\}}|dkr~|dkr~tjjd|r| rtjjd|j||}|r|j ||j ||r||_|_ ||_ ||_ |S)Nz(doctype object owned by another DOM treezElement with no namer/z$http://www.w3.org/XML/1998/namespacezillegal use of 'xml' prefixz(illegal use of prefix without namespaces) r3r/r0WrongDocumentErr_create_documentZInvalidCharacterErrrrcreateElementNSr5rOdoctyperR) r rrrrOruZadd_root_elementrsrrr r r createDocument~s4         z DOMImplementation.createDocumentcCst|}||_||_|S)N)r0r+r,)r rr+r,rOr r r createDocumentTypesz$DOMImplementation.createDocumentTypecCs|j|dr|SdSdS)N)rS)r rTr r r rZs zDOMImplementation.getInterfacecCstS)N)Document)r r r r rMsz"DOMImplementation._create_document)rErF)rErG)rEN)r/rF)r/rG)r/N)rHrI)rHN) rorprqrKrSrPrQrZrMr r r r rDns-rDc@sXeZdZdZddZddZddZdd Zd d Zd d Z ddZ ddZ ddZ dS) ElementInforcCs ||_dS)N)r)r rr r r rszElementInfo.__init__cCstS)N)r)r anamer r r rszElementInfo.getAttributeTypecCstS)N)r)r rrrwr r r rszElementInfo.getAttributeTypeNScCsdS)NFr )r r r r r"szElementInfo.isElementContentcCsdS)NFr )r r r r isEmptyszElementInfo.isEmptycCsdS)NFr )r rTr r r rszElementInfo.isIdcCsdS)NFr )r rrrwr r r rszElementInfo.isIdNScCs|jS)N)r)r r r r rszElementInfo.__getstate__cCs ||_dS)N)r)r rr r r rszElementInfo.__setstate__N)r) rorprqrrrrr"rUrrrrr r r r rSs rScCs>|jtjkr|jjd|_nt|r:|jjjd|j_dS)N)rr r _id_cacheclear_id_search_stackrxrO)rAr r r r:s    r:c@sreZdZdMZejejejejfZ e Z ej Z dZdZdZdZdZZdZdZdZdZdZdZdZd Zd d Zd d ZddZddZddZ ddZ!ddZ"ddZ#ddZ$ddZ%ddZ&d d!Z'd"d#Z(d$d%Z)d&d'Z*d(d)Z+d*d+Z,d,d-Z-d.d/Z.d0d1Z/d2d3Z0d4d5Z1d6d7Z2d8d9Z3d:d;Z4dd?Z6d@dAZ7dBdCZ8dDdEZ9dFdGZ:dNdIdJZ;dKdLZ|jj||jtj kr^|j r^tjjdtj ||S)Nz%s cannot be child of %sz two document elements disallowed) rr.r/r0r1r2r3r4r rJ_get_documentElementr5)r rAr r r r52s    zDocument.appendChildc CsVy|jj|Wntk r.tjjYnXd|_|_d|_|j |krRd|_ |S)N) r$rEr7r/r0r8r<r=r3documentElement)r rCr r r r4Bs  zDocument.removeChildcCs$x|jD]}|jtjkr|SqWdS)N)r$rr rJ)r rAr r r rcNs  zDocument._get_documentElementcCs(|jdk r|jjd|_tj|dS)N)rOrHr )r r r r rHSs  zDocument.unlinkcCs|sdS|jjddd}|j|_|j|_|j|_xL|jD]B}t|||}|jj||jt j krbn|jt j krt||_ ||_ q8W|jtjjj|||S)N)rRrPrr_rUr$rNrIrr rr@rOr3rjr/r0r5r6)r rPr;rZ childcloner r r rQYs"       zDocument.cloneNodecCst}||_|S)N)rrO)r rbr r r createDocumentFragmentnszDocument.createDocumentFragmentcCst|}||_|S)N)rrO)r rr=r r r createElementsszDocument.createElementcCs(t|tstdt}||_||_|S)Nznode contents must be a string)rrrrrGrO)r rGtr r r createTextNodexs  zDocument.createTextNodecCs(t|tstdt}||_||_|S)Nznode contents must be a string)rrrr%rGrO)r rGr@r r r createCDATASections  zDocument.createCDATASectioncCst|}||_|S)N)r$rO)r rGr@r r r createCommentszDocument.createCommentcCst||}||_|S)N)rrO)r rrGpr r r createProcessingInstructions z$Document.createProcessingInstructioncCst|}||_d|_|S)Nr)rrOr)r rar r r createAttributeszDocument.createAttributecCs"t|\}}t|||}||_|S)N)rrrO)r rrrrsrwr=r r r rNs  zDocument.createElementNScCs*t|\}}t||||}||_d|_|S)Nr)rrrOr)r rrrrsrwrmr r r createAttributeNSs  zDocument.createAttributeNScCst||||}||_|S)N)r8rO)r rr+r,r9r=r r r _create_entityszDocument._create_entitycCst|||}||_|S)N)r7rO)r rr+r,rr r r _create_notations zDocument._create_notationcCs||jkr|j|S|jp|js$dS|j}|dkrB|jg}||_n|sJdSd}x>|r|j}|jdd|jD|j|}|r@x|j j D]}|j r|j |j |j r||j|j<|j|kr|}n|jsPq|j|jr ||j|j<|j|kr|}n |js:Pq|jr||j|j<|j|kr.|}q|jdkrPqWnB|jrx8|j j D]*}|jrT||j|j<|j|krT|}qTW|dk rRPqRW|S)NcSsg|]}|jtkr|qSr )rr9).0rMr r r sz+Document.getElementById..r()rVrYrrXrdpopextendr$rrrrrrrwrrrrr)r rstackresultrArrr r r getElementByIdsZ               zDocument.getElementByIdcCst||tS)N)rrk)r rr r r rszDocument.getElementsByTagNamecCst|||tS)N)rrk)r rrrwr r r rszDocument.getElementsByTagNameNScCs|jj||S)N)rRrS)r rTrUr r r rVszDocument.isSupportedcCs>|jtjkrtjjdn|jtjkr2tjjdt|||S)Nzcannot import document nodesz!cannot import document type nodes)rr rr/r0NotSupportedErrr@rN)r rArPr r r importNodes    zDocument.importNodercCsN|dkr|jd|n|jd||fx|jD]}|j||||q2WdS)Nzz%%s)r~r$r)r r"r rr!rrAr r r rs   zDocument.writexmlcCsJ|j|k r tjjd||jf|jtjtjfkr>tjjd|t krd|kr|j dd\}}|dkr|tjj krtjj dq|dkr|tjj kr|jtjkrtjj dd}|}nd}d}|jtjkr|j }|dk r|j}|j|nd}||_||_||_||_|jtjkr||_n*||_|dk rF|j||rF|j||S)Nz?cannot rename nodes from other documents; expected %s, found %sz8renameNode() only applies to element and attribute nodesrr(rzillegal use of 'xmlns' prefixz$illegal use of the 'xmlns' attribute)rOr/r0rLrr rJrryrrrrrrrrsrrrrrrrr)r rrrrrsrwrZis_idr r r renameNodesR         zDocument.renameNode)rYrOrXr$rV)rrrN)=rorprqrr rJrrr@r.rDrRrrrrrr3r=r<r:rr_rUrar]r[rrrrArZr\rBr^r`rbrCr5r4rcrHrQrerfrhrirjrlrnrNrorprqrxrrrVrzrr{r r r r rRsh    : rRrdz#Top-level element of this document.c Cs|jj|rtjjj}n tjjj}|jtj kr|j |j |j }x>|j jD]0}|j|j |j |j|j|j |j}|j|_qJW|rx$|jD]}t|||}|j|qWn|jtjkr|j}|rx$|jD]}t|||}|j|qWn|jtjkr |j|j}n|jtjkr*|j|j}n|jtjkrL|j|j |j}nr|jtj!krj|j"|j}nT|jtj#kr|j$|j |j }d|_|j|_n$|jtj%krtjjj}|j&j'|j(|j)|j*}||_|rg|j+_,g|j-_,xR|j-j,D]F} t.| j | j)| j*} || _|j-j,j/| t0| dr| j1|| | qWx|j+j,D]b} t2| j | j)| j*| j3} | j4| _4| j5| _5| j6| _6|| _|j+j,j/| t0| drB| j1|| | qBWntjj7dt8|t0|dr|j1||||S)NTrjzCannot clone node %s)9rOrYr/r0r5r6Z NODE_IMPORTEDrr rJrNrrrrrrrrrwrr$rNr5r+rerFrhrGrrirrlrrrjrror@rRrQrr+r,r1r(r2r7rIrdrjr8r9r:rrUryr2) rArPZnewOwnerDocumentrgr;rrmrMr@rr<r=r>r r r rNAs|                rNcCs,|jdd}t|dkr|Sd|dfSdS)Nrr(r)rr)rZfieldsr r r rs  rcCs,|||}|j\}}|j||j|S)N)ZgetEventZ expandNoderW)funcargskwargsZeventsZtoktypeZrootNoder r r _do_pulldom_parses    rcCsJ|dkr$| r$ddlm}|j|Sddlm}t|j|f||dSdS)Nr) expatbuilder)pulldom)parserbufsize)xml.domrparserr)filerrrrr r r rs     rcCsB|dkrddlm}|j|Sddlm}t|j|fd|iSdS)Nr)r)rr)rr parseStringrr)stringrrrr r r rs     rcCsB|rs v  y$ w )GU  ><( O*PR __pycache__/minidom.cpython-36.pyc000064400000155050147204745200013051 0ustar003 \@sdZddlZddlZddlmZmZmZmZddlTddl m Z m Z ej j jej j jfZGdddej j Z ee dd d ee d d d ee d dd ddZddZddZddZddZGddde ZGddde Zeeddd eed dd eed d!d Gd"d#d#eZeed$d%d eZGd&d'd'eZeddZGd(d)d)e Zeed*d+d eed d,d d-d.ZGd/d0d0Z Gd1d2d2e e Z!Gd3d4d4e e Z"ee"d$d5d Gd6d7d7e"Z#ee#d8d9d ee#d:d;d dd?Z%Gd@dAdAe"Z&GdBdCdCe#Z'GdDdEdEeZ(ee(d$dFd GdGdHdHZ)GdIdJdJe)e e Z*GdKdLdLe)e Z+GdMdNdNe)e e Z,GdOdPdPe Z-GdQdRdReZ.dSdTZ/GdUdVdVe e Z0ee0dWdXd dYdZZ1d[d\Z2d]d^Z3ded_d`Z4dfdadbZ5dgdcddZ6dS)hacSimple implementation of the Level 1 DOM. Namespaces and other minor Level 2 features are also supported. parse("foo.xml") parseString("") Todo: ===== * convenience methods for getting elements and text. * more testing * bring some of the writer and linearizer code into conformance with this interface * SAX 2 namespaces N)EMPTY_NAMESPACE EMPTY_PREFIXXMLNS_NAMESPACEdomreg)*)DOMImplementationLS DocumentLSc@seZdZdZdZdZdZdZeZ ddZ d2ddZ d3dd Z d d Z d d ZddZddZddZddZddZddZddZddZddZd d!Zd"d#Zd$d%Zd&d'Zd(d)Zd*d+Zd,d-Zd.d/Zd0d1Z dS)4NodeNcCsdS)NT)selfr r '/usr/lib64/python3.6/xml/dom/minidom.py__bool__+sz Node.__bool__cCs|jdd|S)N) toprettyxml)r encodingr r r toxml.sz Node.toxml  cCsx|dkrtj}ntjtj|ddd}|jtjkrH|j|d|||n|j|d|||dkrh|jS|j jSdS)Nxmlcharrefreplacer)rerrorsnewliner) ioStringIO TextIOWrapperBytesIOnodeTyper DOCUMENT_NODEwritexmlgetvaluedetach)r indentnewlrwriterr r r r1s   zNode.toprettyxmlcCs t|jS)N)bool childNodes)r r r r hasChildNodesCszNode.hasChildNodescCs|jS)N)r$)r r r r _get_childNodesFszNode._get_childNodescCs|jr|jdSdS)Nr)r$)r r r r _get_firstChildIszNode._get_firstChildcCs|jr|jdSdS)N)r$)r r r r _get_lastChildMszNode._get_lastChildc Cs|j|jkr0xt|jD]}|j||qW|S|j|jkrXtjjdt |t |f|j dk rn|j j ||dkr|j |ny|jj |}Wntk rtjjYnX|jtkrt||jj||||_||_|r|j|d}||_||_nd|_||_ |S)Nz%s cannot be child of %sr()rDOCUMENT_FRAGMENT_NODEtupler$ insertBefore_child_node_typesxmldomHierarchyRequestErrrepr parentNode removeChild appendChildindex ValueError NotFoundErr_nodeTypes_with_children_clear_id_cacheinsert nextSiblingpreviousSibling)r newChildrefChildcr6noder r r r-Qs6      zNode.insertBeforecCs|j|jkr.xt|jD]}|j|qW|S|j|jkrXtjjdt |t |fn|jt krjt ||j dk r|j j |t||d|_|S)Nz%s cannot be child of %s)rr+r,r$r5r.r/r0r1r2r9r:r3r4 _append_childr<)r rAr@r r r r5qs      zNode.appendChildc Cs|j|jkr(|j}|j||j||S|j|jkrPtjjdt |t |f||kr\dS|j dk rr|j j|y|j j |}Wnt k rtjjYnX||j |<||_ d|_ |jtks|jtkrt||j|_|j|_d|_d|_|jr||j_|jr||j_|S)Nz%s cannot be child of %s)rr+r<r4r-r.r/r0r1r2r3r$r6r7r8r9r:r=)r r>oldChildr?r6r r r replaceChilds<         zNode.replaceChildc Csy|jj|Wntk r.tjjYnX|jdk rD|j|j_|jdk rX|j|j_d|_|_|jt krvt |d|_ |S)N) r$remover7r/r0r8r<r=rr9r:r3)r rCr r r r4s      zNode.removeChildcCsg}x|jD]}|jtjkr|jsL|r2|j|d_|jrB|j|j_|jq|r|dj|jkr|d}|j|j|_|j|_|jr||j_|jq|j|q |j||jtj kr |j q W||jdd<dS)Nr(r)r)r)) r$rr TEXT_NODEdatar<r=unlinkappend ELEMENT_NODE normalize)r LchildrAr r r rKs*          zNode.normalizecCst|||jp|S)N) _clone_node ownerDocument)r deepr r r cloneNodeszNode.cloneNodecCs|jjj||S)N)rOimplementation hasFeature)r featureversionr r r isSupportedszNode.isSupportedcCsdS)Nr )r r r r _get_localNameszNode._get_localNamecCs||kS)Nr )r otherr r r isSameNodeszNode.isSameNodecCs|j|dr|SdSdS)N)rV)r rTr r r getInterfaces zNode.getInterfacec Cs,y|j|dSttfk r&dSXdS)Nr) _user_dataAttributeErrorKeyError)r keyr r r getUserDataszNode.getUserDatac Csnd}y |j}Wntk r,i}||_YnX||krB||d}|dkr^d}|dk rj||=n ||f||<|S)Nr)r[r\)r r^rGhandlerolddr r r setUserDatas    zNode.setUserDatacCsHt|drDx8t|jjD]&\}\}}|dk r|j|||||qWdS)Nr[)hasattrlistr[itemsZhandle)r operationsrcdstr^rGr`r r r _call_user_data_handlers zNode._call_user_data_handlercCsBd|_|_|jr2x|jD] }|jqWt|_d|_d|_dS)N)r3rOr$rHNodeListr=r<)r rMr r r rHs   z Node.unlinkcCs|S)Nr )r r r r __enter__szNode.__enter__cCs |jdS)N)rH)r ZetZevtbr r r __exit__sz Node.__exit__)N)rrN)!__name__ __module__ __qualname__ namespaceURIr3rOr<r=rprefixr rrr%r&r'r*r-r5rDr4rKrQrVrWrYrZr_rcrjrHrlrnr r r r r "s:      r firstChildzFirst child node, or None.)doc lastChildzLast child node, or None. localNamez"Namespace-local name of this node.cCs2|j}|r|d}||_||_|j|||_dS)Nr(r))r$r=r<rIr3)r rAr$Zlastr r r rBs rBcCs(x"|dk r"|jtjkrdS|j}qWdS)NTF)rr rr3)rAr r r _in_document&s    rxcCs6|r2|jddjddjddjdd}|j|d S) zWrites datachars to writer.&z&z>N)replacewrite)r"rGr r r _write_data.srcCsHxB|jD]8}|jtjkr4|dks*|j|kr4|j|t|||qW|S)Nr)r$rr rJtagNamerI_get_elements_by_tagName_helper)parentnamercrAr r r r5s    rcCs\xV|jD]L}|jtjkr|dks*|j|krF|dks<|j|krF|j|t||||qW|S)Nr)r$rr rJrwrrrI"_get_elements_by_tagName_ns_helper)rZnsURIrwrrAr r r r=s   rc@sJeZdZejZdZdZdZdZ ej ej ej ej ejejejfZddZdS)DocumentFragmentz#document-fragmentNcCs t|_dS)N)rkr$)r r r r __init__TszDocumentFragment.__init__)rorprqr r+rnodeName nodeValue attributesr3rJrFCDATA_SECTION_NODEENTITY_REFERENCE_NODEPROCESSING_INSTRUCTION_NODE COMMENT_NODE NOTATION_NODEr.rr r r r rFsrc@seZdZd#ZejZd Zd Zd Z ej ej fZ e d d fd d Zd dZddZddZddZeeeZZddZddZeeeZZddZddZeeeZddZdd Zd!d"Zd S)$Attr_name_valuerr_prefixr$ _localNamerO ownerElementNFcCs2d|_||_||_||_t|_|jjtdS)N)rrrrrrkr$rIText)r qNamerrrwrsr r r rbs z Attr.__init__c Cs.y|jStk r(|jjdddSXdS)N:r(r))rr\rsplit)r r r r rWoszAttr._get_localNamecCs|jS)N) specified)r r r r _get_specifieduszAttr._get_specifiedcCs|jS)N)r)r r r r _get_namexszAttr._get_namecCs||_|jdk rt|jdS)N)rrr:)r valuer r r _set_name{s zAttr._set_namecCs|jS)N)r)r r r r _get_valueszAttr._get_valuecCs6||_||jd_|jdk r&t|j||jd_dS)Nr)rr$rGrr:)r rr r r _set_values    zAttr._set_valuecCs|jS)N)r)r r r r _get_prefixszAttr._get_prefixcCsd|j}|dkr&|r&|tkr&tjjd||_|dkr<|j}nd||jf}|jrZt|j||_ dS)Nxmlnsz5illegal use of 'xmlns' prefix for the wrong namespacez%s:%s) rrrr/r0 NamespaceErrrrwrr:r)r rsZnsuriZnewNamer r r _set_prefixs  zAttr._set_prefixcCsz|j}|dk rR|j|j=|j|j|jf=|jrRd|_|jd8_|jj d8_ x|j D] }|j qZW|j dd=dS)NFr() r_attrsr_attrsNSrrrw_is_id_magic_id_nodesrO_magic_id_countr$rH)r elemrMr r r rHs   z Attr.unlinkcCsf|jr dS|j}|j}|dks&|dkr*dS|j|}|dkr@dS|jrV|j|j|jS|j|jSdS)NTF) rrOr_get_elem_inforrisIdNSrwisIdr)r rurinfor r r _get_isIds zAttr._get_isIdcCs\|j}|j}|dks|dkr tS|j|}|dkr6tS|jrL|j|j|jS|j|jSdS)N) rOr_no_typerrrgetAttributeTypeNSrwgetAttributeTyper)r rurrr r r _get_schemaTypes zAttr._get_schemaType)rrrrrr$rrOr) rorprq __slots__r ATTRIBUTE_NODErrrrrFrr.rrrWrrrpropertyrrrrrrrrrsrHrrr r r r rXs.   rrz True if this attribute is an ID.z'Namespace-local name of this attribute. schemaTypezSchema type for this attribute.c@seZdZdZd NamedNodeMapaThe attribute list is a transient interface to the underlying dictionaries. Mutations here will change the underlying element's dictionary. Ordering is imposed artificially and does not reflect the order of attributes as found in an input document. rr _ownerElementcCs||_||_||_dS)N)rrr)r attrsZattrsNSrr r r rszNamedNodeMap.__init__cCs t|jS)N)lenr)r r r r _get_lengthszNamedNodeMap._get_lengthc Cs0y|t|jj|Stk r*dSXdS)N)rerkeys IndexError)r r6r r r itemszNamedNodeMap.itemcCs.g}x$|jjD]}|j|j|jfqW|S)N)rvaluesrIrr)r rLrAr r r rfszNamedNodeMap.itemscCs4g}x*|jjD]}|j|j|jf|jfqW|S)N)rrrIrrrwr)r rLrAr r r itemsNSszNamedNodeMap.itemsNScCs"t|tr||jkS||jkSdS)N) isinstancestrrr)r r^r r r __contains__s  zNamedNodeMap.__contains__cCs |jjS)N)rr)r r r r rszNamedNodeMap.keyscCs |jjS)N)rr)r r r r keysNSszNamedNodeMap.keysNScCs |jjS)N)rr)r r r r rszNamedNodeMap.valuesNcCs|jj||S)N)rget)r rrr r r r szNamedNodeMap.getcCs:|jt|ddkrdSt|t|kt|t|kSdS)Nrr)rgetattrid)r rXr r r _cmpszNamedNodeMap._cmpcCs|j|dkS)Nr)r)r rXr r r __eq__szNamedNodeMap.__eq__cCs|j|dkS)Nr)r)r rXr r r __ge__szNamedNodeMap.__ge__cCs|j|dkS)Nr)r)r rXr r r __gt__szNamedNodeMap.__gt__cCs|j|dkS)Nr)r)r rXr r r __le__szNamedNodeMap.__le__cCs|j|dkS)Nr)r)r rXr r r __lt__!szNamedNodeMap.__lt__cCs"t|tr|j|S|j|SdS)N)rr,rr)r attname_or_tupler r r __getitem__$s  zNamedNodeMap.__getitem__c Csvt|trRy|j|}Wn0tk rHt|}|jj|_|j|YnX||_n t|tsdt d|}|j|dS)Nz%value must be a string or Attr object) rrrr]rrrO setNamedItemr TypeError)r attnamerrAr r r __setitem__+s   zNamedNodeMap.__setitem__c Cs$y |j|Stk rdSXdS)N)rr])r rr r r getNamedItem:s zNamedNodeMap.getNamedItemc Cs(y|j||fStk r"dSXdS)N)rr])r rrrwr r r getNamedItemNS@szNamedNodeMap.getNamedItemNScCsX|j|}|dk rJt|j|j|j=|j|j|jf=t|drFd|_ |St j j dS)Nr) rr:rrrrrrrwrdrr/r0r8)r rnr r r removeNamedItemFs    zNamedNodeMap.removeNamedItemcCsZ|j||}|dk rLt|j|j|j|jf=|j|j=t|drHd|_ |St j j dS)Nr) rr:rrrrrwrrrdrr/r0r8)r rrrwrr r r removeNamedItemNSRs    zNamedNodeMap.removeNamedItemNScCstt|ts&tjjdt|t|f|jj|j}|r@|j ||j|j<||j |j |j f<|j |_t|j|S)Nz%s cannot be child of %s)rrr/r0r1r2rrrrHrrrrwrrr:)r rArar r r r^s   zNamedNodeMap.setNamedItemcCs |j|S)N)r)r rAr r r setNamedItemNSkszNamedNodeMap.setNamedItemNScCs||}t|j|jdS)N)r:rrH)r rrAr r r __delitem__ns zNamedNodeMap.__delitem__cCs|j|j|jfS)N)rrr)r r r r __getstate__sszNamedNodeMap.__getstate__cCs|\|_|_|_dS)N)rrr)r stater r r __setstate__vszNamedNodeMap.__setstate__)rrr)N)!rorprq__doc__rrrrrfrrrrrr__len__rrrrrrrrrrrrrrrrrr r r r rs<    rZlengthz$Number of nodes in the NamedNodeMap.c@s0eZdZd ZddZddZddZd d Zd S) TypeInfo namespacercCs||_||_dS)N)rr)r rrr r r rszTypeInfo.__init__cCs2|jrd|jj|j|jfSd|jj|jfSdS)Nz<%s %r (from %r)>z<%s %r>)r __class__ror)r r r r __repr__s  zTypeInfo.__repr__cCs|jS)N)r)r r r r rszTypeInfo._get_namecCs|jS)N)r)r r r r _get_namespaceszTypeInfo._get_namespaceN)rr)rorprqrrrrrr r r r rs rc @s eZdZdDZejZd ZeZ dZ ejej ej ej ejejfZed d fddZddZddZddZddZddZddZddZdd Zd!d"Zd#d$Zd%d&ZeZd'd(Zd)d*Z d+d,Z!e!Z"d-d.Z#d/d0Z$d1d2Z%d3d4Z&d5d6Z'dEd8d9Z(d:d;Z)dd?Z+d@dAZ,dBdCZ-d S)FElementrOr3rrrsrrrr$rrr<r=NrcCsBd|_||_|_||_||_t|_d|_|_d|_ d|_ dS)N) r3rrrsrrrkr$r<r=rr)r rrrrsrwr r r rs  zElement.__init__cCs|jdkri|_i|_dS)N)rr)r r r r _ensure_attributess zElement._ensure_attributesc Cs.y|jStk r(|jjdddSXdS)Nrr(r))rr\rr)r r r r rWszElement._get_localNamecCs|jS)N)r)r r r r _get_tagNameszElement._get_tagNamecCsD|jdk r*xt|jjD] }|jqWd|_d|_tj|dS)N)rrerrHrr )r attrr r r rHs   zElement.unlinkc Cs4|jdkrdSy |j|jStk r.dSXdS)Nr)rrr])r rr r r getAttributes   zElement.getAttributec Cs8|jdkrdSy|j||fjStk r2dSXdS)Nr)rrr])r rrrwr r r getAttributeNSs  zElement.getAttributeNScCsV|j|}|dkr4t|}||_|j|_|j|n||jkrR||_|jrRt|dS)N)getAttributeNoderrrOsetAttributeNoderr:)r rrrr r r setAttributes   zElement.setAttributecCst|\}}|j||}|dkrHt||||}||_|j|_|j|n4||jkrf||_|jrft||j|kr|||_||_ dS)N) _nssplitgetAttributeNodeNSrrrOrrr:rsr)r rr qualifiedNamerrs localnamerr r r setAttributeNSs     zElement.setAttributeNScCs|jdkrdS|jj|S)N)rr)r Zattrnamer r r rs zElement.getAttributeNodecCs|jdkrdS|jj||fS)N)rr)r rrrwr r r rs zElement.getAttributeNodeNScCs|jd|fkrtjjd|j|jj|jd}|dk rD|j||j j|j |j fd}|dk rt||k rt|j|t ||||k r|S||k r|SdS)Nzattribute node already owned) rr/r0ZInuseAttributeErrrrrrremoveAttributeNoderrrrw_set_attribute_node)r rZold1Zold2r r r rs    zElement.setAttributeNodec CsP|jdkrtjjy|j|}Wntk r@tjjYnX|j|dS)N)rr/r0r8rr]r)r rrr r r removeAttributes  zElement.removeAttributec CsT|jdkrtjjy|j||f}Wntk rDtjjYnX|j|dS)N)rr/r0r8r]r)r rrrwrr r r removeAttributeNS%s  zElement.removeAttributeNSc Cs^|dkrtjjy|j|jWntk r@tjjYnXt||j|j|_dS)N) r/r0r8rrr]r:rHrO)r rAr r r r.s zElement.removeAttributeNodecCs|jdkrdS||jkS)NF)r)r rr r r hasAttribute=s zElement.hasAttributecCs|jdkrdS||f|jkS)NF)r)r rrrwr r r hasAttributeNSBs zElement.hasAttributeNScCst||tS)N)rrk)r rr r r getElementsByTagNameGszElement.getElementsByTagNamecCst|||tS)N)rrk)r rrrwr r r getElementsByTagNameNSJszElement.getElementsByTagNameNScCsd|jt|fS)Nz)rr)r r r r rNszElement.__repr__rc Cs|j|d|j|j}t|j}x4|D],}|jd|t|||j|jdq.W|jr|jdt|jdkr|jdj t j kr|jdj |dddn8|j|x"|jD]}|j |||||qW|j||jd|j|fn|jd |dS) Nrzz %s="r{r|r(rrz%sz/>%s) r~r_get_attributessortedrrrr$rrr rFr) r r"r addindentr!rZa_namesZa_namerAr r r rQs$      zElement.writexmlcCs|jt|j|j|S)N)rrrr)r r r r rlszElement._get_attributescCs|jr dSdSdS)NTF)r)r r r r hasAttributespszElement.hasAttributescCs|j|}|j|dS)N)rsetIdAttributeNode)r ridAttrr r r setIdAttributexs zElement.setIdAttributecCs|j||}|j|dS)N)rr)r rrrwrr r r setIdAttributeNS|s zElement.setIdAttributeNScCsl|dks|j|j r tjjt|dk r6tjj|jshd|_|jd7_|j j d7_ t |dS)NTr() rYrr/r0r8_get_containing_entrefNoModificationAllowedErrrrrOrr:)r rr r r rs   zElement.setIdAttributeNode) rOr3rrrsrrrr$rrr<r=)rrr).rorprqrr rJrrrrrrrrFrrr.rrrrWrrHrrrrrrrZsetAttributeNodeNSrrrZremoveAttributeNodeNSrrrrrrrrrrrr r r r rsT      rrz*NamedNodeMap of attributes on the element.z%Namespace-local name of this element.cCs8t||j||j|j<||j|j|jf<||_dS)N)r:rrrrrrrwr)elementrr r r rs  rc@sfeZdZdZfZdZeZdZdZ ddZ ddZ ddZ d d Z d d Zd dZddZddZdS) ChildlesszMixin that makes childless-ness easy to implement and avoids the complexity of the Node methods that deal with children. NcCsdS)Nr )r r r r r'szChildless._get_firstChildcCsdS)Nr )r r r r r*szChildless._get_lastChildcCstjj|jddS)Nz nodes cannot have children)r/r0r1r)r rAr r r r5szChildless.appendChildcCsdS)NFr )r r r r r%szChildless.hasChildNodescCstjj|jddS)Nz nodes do not have children)r/r0r1r)r r>r?r r r r-szChildless.insertBeforecCstjj|jddS)Nz nodes do not have children)r/r0r8r)r rCr r r r4szChildless.removeChildcCsdS)Nr )r r r r rKszChildless.normalizecCstjj|jddS)Nz nodes do not have children)r/r0r1r)r r>rCr r r rDszChildless.replaceChild)rorprqrrrZ EmptyNodeListr$rtrvr'r*r5r%r-r4rKrDr r r r rsrc@s\eZdZejZdZddZddZddZ e ee Z d d Z d d Z e e e ZdddZdS)ProcessingInstructiontargetrGcCs||_||_dS)N)r rG)r r rGr r r rszProcessingInstruction.__init__cCs|jS)N)rG)r r r r _get_nodeValuesz$ProcessingInstruction._get_nodeValuecCs ||_dS)N)rG)r rr r r _set_nodeValuesz$ProcessingInstruction._set_nodeValuecCs|jS)N)r )r r r r _get_nodeNamesz#ProcessingInstruction._get_nodeNamecCs ||_dS)N)r )r rr r r _set_nodeNamesz#ProcessingInstruction._set_nodeNamercCs|jd||j|j|fdS)Nz %s%s)r~r rG)r r"r rr!r r r rszProcessingInstruction.writexmlN)r rG)rrr)rorprqr rrrrr r rrr r rrr r r r rs  rc@sreZdZdZddZdd ZeZd d Zd d Ze eeZ Z ddZ ddZ ddZddZddZddZdS) CharacterData_datarOr3r=r<cCs,d|_|_d|_|_d|_tj|dS)Nr)rOr3r=r<rr r)r r r r rs  zCharacterData.__init__cCs t|jS)N)rrG)r r r r rszCharacterData._get_lengthcCs|jS)N)r)r r r r _get_dataszCharacterData._get_datacCs ||_dS)N)r)r rGr r r _set_dataszCharacterData._set_datacCs6|j}t|dkrd}nd}d|jj|dd|fS)N z...rzr)rGrrro)r rGZ dotdotdotr r r rs  zCharacterData.__repr__cCsT|dkrtjjd|t|jkr.tjjd|dkrBtjjd|j|||S)Nrzoffset cannot be negativez#offset cannot be beyond end of datazcount cannot be negative)r/r0 IndexSizeErrrrG)r offsetcountr r r substringDatas   zCharacterData.substringDatacCs|j||_dS)N)rG)r argr r r appendDataszCharacterData.appendDatacCsZ|dkrtjjd|t|jkr.tjjd|rVd|jd|||j|df|_dS)Nrzoffset cannot be negativez#offset cannot be beyond end of dataz%s%s%s)r/r0rrrG)r rrr r r insertDatas  zCharacterData.insertDatacCsl|dkrtjjd|t|jkr.tjjd|dkrBtjjd|rh|jd||j||d|_dS)Nrzoffset cannot be negativez#offset cannot be beyond end of datazcount cannot be negative)r/r0rrrG)r rrr r r deleteDatas   zCharacterData.deleteDatacCsr|dkrtjjd|t|jkr.tjjd|dkrBtjjd|rnd|jd|||j||df|_dS)Nrzoffset cannot be negativez#offset cannot be beyond end of datazcount cannot be negativez%s%s%s)r/r0rrrG)r rrrr r r replaceDatas   zCharacterData.replaceDataN)rrOr3r=r<)rorprqrrrrrrrrGrrrrrrrr r r r rs    rzLength of the string data.c@sHeZdZfZejZdZdZddZ dddZ dd Z d d Z d d Z dS)rz#textNcCs|dks|t|jkr"tjjd|j}|j|d|_|j|_|j}|jr~||jj kr~|dkrp|jj |n|jj |||jd||_|S)Nrzillegal offset value) rrGr/r0rrrOr<r3r$r5r-)r rZnewTextnextr r r splitText0s zText.splitTextrcCst|d||j|fdS)Nz%s%s%s)rrG)r r"r rr!r r r r?sz Text.writexmlcCs|jg}|j}x6|dk rD|jtjtjfkr@|jd|j|j}qPqW|j}x4|dk r|jtjtjfkr||j|j|j}qNPqNWdj |S)Nrr) rGr=rr rFrr;r<rIjoin)r rLrr r r _get_wholeTextDs   zText._get_wholeTextcCs|j}|j}x6|dk rB|jtjtjfkr>|j}|j||}qPqW|j}|sX|j|x6|dk r|jtjtjfkr|j}|j||}qZPqZW|r||_|SdSdS)N) r3r=rr rFrr4r<rG)r Zcontentrrrr r r replaceWholeTextVs*     zText.replaceWholeTextcCsF|jjrdSt|}|dkr"dS|jj|}|dkr:dS|jSdS)NF)rGstrip_get_containing_elementrOrisElementContent)r rrr r r !_get_isWhitespaceInElementContentrs  z&Text._get_isWhitespaceInElementContent)rrr)rorprqrr rFrrrrrrr r$r r r r r)s rZisWhitespaceInElementContentzKTrue iff this text node contains only whitespace and is in element content.Z wholeTextz.The text of all logically-adjacent text nodes.cCs.|j}x"|dk r(|jtjkr |S|j}qWdS)N)r3rr rJ)rAr@r r r r"s    r"cCs.|j}x"|dk r(|jtjkr |S|j}qWdS)N)r3rr r)rAr@r r r rs    rc@s(eZdZejZdZddZdddZdS) Commentz#commentcCstj|||_dS)N)rrr)r rGr r r rs zComment.__init__rcCs,d|jkrtd|jd||j|fdS)Nz--z%'--' is not allowed in a comment nodez %s%s)rGr7r~)r r"r rr!r r r rs zComment.writexmlN)rrr) rorprqr rrrrrr r r r r%sr%c@s$eZdZfZejZdZdddZdS) CDATASectionz#cdata-sectionrcCs,|jjddkrtd|jd|jdS)Nz]]>rz$']]>' not allowed in a CDATA sectionz)rGfindr7r~)r r"r rr!r r r rszCDATASection.writexmlN)rrr) rorprqrr rrrrr r r r r&sr&c@s|eZdZdZffddZddZddZdd Zd d Zd d Z ddZ ddZ ddZ ddZ ddZddZddZdS)ReadOnlySequentialNamedNodeMap_seqcCs ||_dS)N)r))r seqr r r rsz'ReadOnlySequentialNamedNodeMap.__init__cCs t|jS)N)rr))r r r r rsz&ReadOnlySequentialNamedNodeMap.__len__cCs t|jS)N)rr))r r r r rsz*ReadOnlySequentialNamedNodeMap._get_lengthcCs"x|jD]}|j|kr|SqWdS)N)r)r)r rrr r r rs  z+ReadOnlySequentialNamedNodeMap.getNamedItemcCs,x&|jD]}|j|kr|j|kr|SqWdS)N)r)rrrw)r rrrwrr r r rs z-ReadOnlySequentialNamedNodeMap.getNamedItemNScCs4t|tr|j|}n |j|}|dkr0t||S)N)rr,rrr])r Z name_or_tuplerAr r r rs    z*ReadOnlySequentialNamedNodeMap.__getitem__c Cs0|dkr dSy |j|Stk r*dSXdS)Nr)r)r)r r6r r r rs  z#ReadOnlySequentialNamedNodeMap.itemcCstjjddS)Nz"NamedNodeMap instance is read-only)r/r0r)r rr r r rsz.ReadOnlySequentialNamedNodeMap.removeNamedItemcCstjjddS)Nz"NamedNodeMap instance is read-only)r/r0r)r rrrwr r r rsz0ReadOnlySequentialNamedNodeMap.removeNamedItemNScCstjjddS)Nz"NamedNodeMap instance is read-only)r/r0r)r rAr r r rsz+ReadOnlySequentialNamedNodeMap.setNamedItemcCstjjddS)Nz"NamedNodeMap instance is read-only)r/r0r)r rAr r r rsz-ReadOnlySequentialNamedNodeMap.setNamedItemNScCs|jgS)N)r))r r r r rsz+ReadOnlySequentialNamedNodeMap.__getstate__cCs|d|_dS)Nr)r))r rr r r rsz+ReadOnlySequentialNamedNodeMap.__setstate__N)r))rorprqrrrrrrrrrrrrrrr r r r r(s  r(z&Number of entries in the NamedNodeMap.c@s,eZdZdZd ZddZddZdd Zd S) Identifiedz@Mix-in class that supports the publicId and systemId attributes.publicIdsystemIdcCs||_||_dS)N)r,r-)r r,r-r r r _identified_mixin_initsz!Identified._identified_mixin_initcCs|jS)N)r,)r r r r _get_publicIdszIdentified._get_publicIdcCs|jS)N)r-)r r r r _get_systemIdszIdentified._get_systemIdN)r,r-)rorprqrrr.r/r0r r r r r+s r+c@sHeZdZejZdZdZdZdZ dZ ddZ ddZ ddZ d d d ZdS) DocumentTypeNcCs2t|_t|_|r&t|\}}||_|j|_dS)N)r(entities notationsrrr)r rrsrr r r r s  zDocumentType.__init__cCs|jS)N)internalSubset)r r r r _get_internalSubsetsz DocumentType._get_internalSubsetcCs|jdkrtd}|j|_|j|_tjjj}|rg|j_ g|j _ x>|j j D]2}t |j|j |j }|j j j||j|||qJWxZ|jj D]N}t|j|j |j |j}|j|_|j|_|j|_|jj j||j|||qW|j||||SdSdS)N)rOr1rrr/r0UserDataHandler NODE_CLONEDr2r)r3Notationr,r-rIrjEntity notationNameactualEncodingrrU)r rPclonergrnotationeentityr r r rQs.  zDocumentType.cloneNodercCs|jd|j|j|jr8|jd||j||jfn|jrR|jd||jf|jdk r||jd|j|j|jd|jd|dS)Nz r r r r5UszEntity.appendChildcCstjjddS)Nz+cannot insert children below an entity node)r/r0r1)r r>r?r r r r-YszEntity.insertBeforecCstjjddS)Nz*cannot remove children from an entity node)r/r0r1)r rCr r r r4]szEntity.removeChildcCstjjddS)Nz)cannot replace children of an entity node)r/r0r1)r r>rCr r r rDaszEntity.replaceChild)rorprqrr Z ENTITY_NODErrr;rrUrrBrCrDr5r-r4rDr r r r r9=sr9c@seZdZejZdZddZdS)r8NcCs||_|j||dS)N)rr.)r rr,r-r r r riszNotation.__init__)rorprqr rrrrr r r r r8esr8c @sHeZdZddddddddgZdd Zd d Zd d ZddZddZdS)DOMImplementationcore1.02.0Nr/ls-load3.0cCs|dkr d}|j|f|jkS)Nr)lower _features)r rTrUr r r rSyszDOMImplementation.hasFeaturec Cs|r|jdk rtjjd|j}|dko8|dko8|dk }| rR|rRtjjd|rt|\}}|dkr~|dkr~tjjd|r| rtjjd|j||}|r|j ||j ||r||_|_ ||_ ||_ |S)Nz(doctype object owned by another DOM treezElement with no namer/z$http://www.w3.org/XML/1998/namespacezillegal use of 'xml' prefixz(illegal use of prefix without namespaces) r3r/r0WrongDocumentErr_create_documentZInvalidCharacterErrrrcreateElementNSr5rOdoctyperR) r rrrrPruZadd_root_elementrsrrr r r createDocument~s4         z DOMImplementation.createDocumentcCst|}||_||_|S)N)r1r,r-)r rr,r-rPr r r createDocumentTypesz$DOMImplementation.createDocumentTypecCs|j|dr|SdSdS)N)rS)r rTr r r rZs zDOMImplementation.getInterfacecCstS)N)Document)r r r r rNsz"DOMImplementation._create_document)rFrG)rFrH)rFN)r/rG)r/rH)r/N)rIrJ)rIN) rorprqrLrSrQrRrZrNr r r r rEns-rEc@s\eZdZdZdZddZddZddZd d Zd d Z d dZ ddZ ddZ ddZ dS) ElementInfozObject that represents content-model information for an element. This implementation is not expected to be used in practice; DOM builders should provide implementations which do the right thing using information available to it. rcCs ||_dS)N)r)r rr r r rszElementInfo.__init__cCstS)N)r)r anamer r r rszElementInfo.getAttributeTypecCstS)N)r)r rrrwr r r rszElementInfo.getAttributeTypeNScCsdS)NFr )r r r r r#szElementInfo.isElementContentcCsdS)zQReturns true iff this element is declared to have an EMPTY content model.Fr )r r r r isEmptyszElementInfo.isEmptycCsdS)z7Returns true iff the named attribute is a DTD-style ID.Fr )r rUr r r rszElementInfo.isIdcCsdS)z|jtjkr|jjd|_nt|r:|jjjd|j_dS)N)rr r _id_cacheclear_id_search_stackrxrO)rAr r r r:s    r:c@sreZdZdMZejejejejfZ e Z ej Z dZdZdZdZdZZdZdZdZdZdZdZdZd Zd d Zd d ZddZddZddZ ddZ!ddZ"ddZ#ddZ$ddZ%ddZ&d d!Z'd"d#Z(d$d%Z)d&d'Z*d(d)Z+d*d+Z,d,d-Z-d.d/Z.d0d1Z/d2d3Z0d4d5Z1d6d7Z2d8d9Z3d:d;Z4dd?Z6d@dAZ7dBdCZ8dDdEZ9dFdGZ:dNdIdJZ;dKdLZ|jj||jtj kr^|j r^tjjdtj ||S)Nz%s cannot be child of %sz two document elements disallowed) rr.r/r0r1r2r3r4r rJ_get_documentElementr5)r rAr r r r52s    zDocument.appendChildc CsVy|jj|Wntk r.tjjYnXd|_|_d|_|j |krRd|_ |S)N) r$rEr7r/r0r8r<r=r3documentElement)r rCr r r r4Bs  zDocument.removeChildcCs$x|jD]}|jtjkr|SqWdS)N)r$rr rJ)r rAr r r rdNs  zDocument._get_documentElementcCs(|jdk r|jjd|_tj|dS)N)rPrHr )r r r r rHSs  zDocument.unlinkcCs|sdS|jjddd}|j|_|j|_|j|_xx|jD]n}t|||}|jj|sXt |jj ||j t j kr|jdkst n |j t jkr|jdkst ||_||_q8W|jtjjj|||S)N)rRrQrr`rUr$rNrOrYAssertionErrorrIrr rrerArPr3rjr/r0r6r7)r rPr<rZ childcloner r r rQYs&       zDocument.cloneNodecCst}||_|S)N)rrO)r rbr r r createDocumentFragmentnszDocument.createDocumentFragmentcCst|}||_|S)N)rrO)r rr>r r r createElementsszDocument.createElementcCs(t|tstdt}||_||_|S)Nznode contents must be a string)rrrrrGrO)r rGtr r r createTextNodexs  zDocument.createTextNodecCs(t|tstdt}||_||_|S)Nznode contents must be a string)rrrr&rGrO)r rGr@r r r createCDATASections  zDocument.createCDATASectioncCst|}||_|S)N)r%rO)r rGr@r r r createCommentszDocument.createCommentcCst||}||_|S)N)rrO)r r rGpr r r createProcessingInstructions z$Document.createProcessingInstructioncCst|}||_d|_|S)Nr)rrOr)r rar r r createAttributeszDocument.createAttributecCs"t|\}}t|||}||_|S)N)rrrO)r rrrrsrwr>r r r rOs  zDocument.createElementNScCs*t|\}}t||||}||_d|_|S)Nr)rrrOr)r rrrrsrwror r r createAttributeNSs  zDocument.createAttributeNScCst||||}||_|S)N)r9rO)r rr,r-r:r>r r r _create_entityszDocument._create_entitycCst|||}||_|S)N)r8rO)r rr,r-rr r r _create_notations zDocument._create_notationcCs||jkr|j|S|jp|js$dS|j}|dkrB|jg}||_n|sJdSd}x>|r|j}|jdd|jD|j|}|r@x|j j D]}|j r|j |j |j r||j|j<|j|kr|}n|jsPq|j|jr ||j|j<|j|kr|}n |js:Pq|jr||j|j<|j|kr.|}q|jdkrPqWnB|jrx8|j j D]*}|jrT||j|j<|j|krT|}qTW|dk rRPqRW|S)NcSsg|]}|jtkr|qSr )rr9).0rMr r r sz+Document.getElementById..r()rWrZrrYrepopextendr$rrrrrrrwrrrrr)r rstackresultrArrr r r getElementByIdsZ               zDocument.getElementByIdcCst||tS)N)rrk)r rr r r rszDocument.getElementsByTagNamecCst|||tS)N)rrk)r rrrwr r r rszDocument.getElementsByTagNameNScCs|jj||S)N)rRrS)r rTrUr r r rVszDocument.isSupportedcCs>|jtjkrtjjdn|jtjkr2tjjdt|||S)Nzcannot import document nodesz!cannot import document type nodes)rr rr/r0NotSupportedErrrArN)r rArPr r r importNodes    zDocument.importNodercCsN|dkr|jd|n|jd||fx|jD]}|j||||q2WdS)Nzz%%s)r~r$r)r r"r rr!rrAr r r rs   zDocument.writexmlcCsJ|j|k r tjjd||jf|jtjtjfkr>tjjd|t krd|kr|j dd\}}|dkr|tjj krtjj dq|dkr|tjj kr|jtjkrtjj dd}|}nd}d}|jtjkr|j }|dk r|j}|j|nd}||_||_||_||_|jtjkr||_n*||_|dk rF|j||rF|j||S)Nz?cannot rename nodes from other documents; expected %s, found %sz8renameNode() only applies to element and attribute nodesrr(rzillegal use of 'xmlns' prefixz$illegal use of the 'xmlns' attribute)rOr/r0rMrr rJrr{rrrrrrrrsrrrrrrrr)r rrrrrsrwrZis_idr r r renameNodesR         zDocument.renameNode)rZrPrYr$rW)rrrN)=rorprqrr rJrrrAr.rErRrrrrrr3r=r<r;rr`rUrbr^r\rrrrBr[r]rCr_rarcrDr5r4rdrHrQrgrhrjrkrlrnrprOrqrrrsrzrrrVr|rr}r r r r rSsh    : rSrez#Top-level element of this document.c Cs|jj|rtjjj}n tjjj}|jtj kr|j |j |j }x>|j jD]0}|j|j |j |j|j|j |j}|j|_qJW|rx$|jD]}t|||}|j|qWn"|jtjkr|j}|rx$|jD]}t|||}|j|qWn|jtjkr |j|j}n|jtjkr*|j|j}n|jtjkrL|j|j |j}n|jtj!krj|j"|j}nd|jtj#kr|j$|j |j }d|_|j|_n4|jtj%kr|j|k st&tjjj}|j'j(|j)|j*|j+}||_|rg|j,_-g|j._-xR|j.j-D]F} t/| j | j*| j+} || _|j.j-j0| t1| dr| j2|| | qWx|j,j-D]b} t3| j | j*| j+| j4} | j5| _5| j6| _6| j7| _7|| _|j,j-j0| t1| drR| j2|| | qRWntjj8dt9|t1|dr|j2||||S)zo Clone a node and give it the new owner document. Called by Node.cloneNode and Document.importNode TrjzCannot clone node %s):rOrYr/r0r6r7Z NODE_IMPORTEDrr rJrOrrrrrrrrrwrr$rNr5r+rgrFrjrGrrkrrnr rrlrrqrArfrRrRrr,r-r2r)r3r8rIrdrjr9r:r;rrUr{r2) rArPZnewOwnerDocumentrgr<rrorMr@rr=r>r?r r r rNAs~                rNcCs,|jdd}t|dkr|Sd|dfSdS)Nrr(r)rr)rZfieldsr r r rs  rcCs,|||}|j\}}|j||j|S)N)ZgetEventZ expandNoderX)funcargskwargsZeventsZtoktypeZrootNoder r r _do_pulldom_parses    rcCsJ|dkr$| r$ddlm}|j|Sddlm}t|j|f||dSdS)z3Parse a file into a DOM by filename or file object.Nr) expatbuilder)pulldom)parserbufsize)xml.domrparserr)filerrrrr r r rs     rcCsB|dkrddlm}|j|Sddlm}t|j|fd|iSdS)z&Parse a file into a DOM from a string.Nr)r)rr)rr parseStringrr)stringrrrr r r rs     rcCsB|rs v  y$ w )GU  ><( O*PR __pycache__/pulldom.cpython-36.opt-1.pyc000064400000024451147204745200014030 0ustar003 \-@sddlZddlZdZdZdZdZdZdZdZ d Z Gd d d ej j Z Gd d d ZGdddZGddde ZdZdddZdddZdS)N START_ELEMENT END_ELEMENTCOMMENTSTART_DOCUMENT END_DOCUMENTPROCESSING_INSTRUCTIONIGNORABLE_WHITESPACE CHARACTERSc@seZdZdZdZd$ddZddZddZdd Zd d Z d d Z ddZ ddZ ddZ ddZddZddZddZddZddZd d!Zd"d#ZdS)%PullDOMNc Cszddlm}||_ddg|_|j|_g|_|jj|_y|jj|_Wnt k rVYnX|dig|_ |j d|_ g|_ dS)Nr) XML_NAMESPACExml) Zxml.domr documentFactory firstEvent lastEvent elementStackappendpushpopAttributeError _ns_contexts_current_contextpending_events)selfrr r'/usr/lib64/python3.6/xml/dom/pulldom.py__init__s     zPullDOM.__init__cCs|jd}|jd=|S)Nr rr)r)rresultrrrr!s z PullDOM.popcCs ||_dS)N)_locator)rZlocatorrrrsetDocumentLocator&szPullDOM.setDocumentLocatorcCsHt|dsg|_|jj|pd|f|jj|jj|px|D]\}}||j||f<qWg|_|\}} |r|dkrr|j|} | rn| d| }n| }|jr|jj||} q|j||} n |jr|jj| } n |jd| } x|jD]\}}|\} } | |kr | dkr| }nd| }|jj | |}| j |nX| rL|j| } | r.| d| }n| }|jj | |}| j |n|jj | }| j |||_ qWt| fdg|jd<|jd|_|j| dS)Nzhttp://www.w3.org/2000/xmlns/r!:r"zxmlns:r )getattrZ_attrsr!rdocumentZcreateElementNS buildDocument createElementitemsZcreateAttributeNSZsetAttributeNodeNScreateAttributesetAttributeNodevaluerrr)rnametagNameattrsZ xmlns_uriZ xmlns_attrsanamer1r&Z localnamer%nodeZa_uriZ a_localnameZqnameattrrrrstartElementNS3sP           zPullDOM.startElementNScCs&t|jfdg|jd<|jd|_dS)Nr )rrr)rr2r3rrr endElementNSlszPullDOM.endElementNScCs~|jr|jj|}n |jd|}x0|jD]$\}}|jj|}||_|j|q*Wt|fdg|jd<|jd|_|j |dS)Nr ) r+r-r,r.r/r1r0rrr)rr2r4r6r5r1r7rrr startElementps   zPullDOM.startElementcCs&t|jfdg|jd<|jd|_dS)Nr )rrr)rr2rrr endElementszPullDOM.endElementcCsN|jr2|jj|}t|fdg|jd<|jd|_nt|fdg}|jj|dS)Nr )r+ createCommentrrrr)rsr6eventrrrcomments   zPullDOM.commentcCsR|jr4|jj||}t|fdg|jd<|jd|_nt||fdg}|jj|dS)Nr )r+createProcessingInstructionrrrr)rtargetdatar6r>rrrprocessingInstructions zPullDOM.processingInstructioncCs.|jj|}t|fdg|jd<|jd|_dS)Nr )r+createTextNoderr)rcharsr6rrrignorableWhitespaces zPullDOM.ignorableWhitespacecCs.|jj|}t|fdg|jd<|jd|_dS)Nr )r+rDr r)rrEr6rrr characterss zPullDOM.characterscCs$|jdkr ddl}|jjjj|_dS)Nr)rZxml.dom.minidomZdomZminidomZDocumentimplementation)rr rrr startDocuments zPullDOM.startDocumentc Cs|jj||d}||_t|fdg|jd<|jd|_|j|x|jD]}|ddtkr|d\}}}|jj||}t|f|d<nD|ddt kr|jj |dd}t |f|d<nt d|dd||jd<||_qFWd|_|j S)Nr rzUnknown pending event ) rZcreateDocumentr+rrrrrr@rr<AssertionErrorZ firstChild) rr&Ztagnamer6e_rArBnrrrr,s$     zPullDOM.buildDocumentcCs t|jfdg|jd<|jdS)Nr )rr+rr)rrrr endDocumentszPullDOM.endDocumentcCs d|_dS)z.clear(): Explicitly release parsing structuresN)r+)rrrrclearsz PullDOM.clear)N)__name__ __module__ __qualname__rr+rrr r'r(r8r9r:r;r?rCrFrGrIr,rNrOrrrrr s& 9  r c@s$eZdZddZddZddZdS) ErrorHandlercCs t|dS)N)print)r exceptionrrrwarningszErrorHandler.warningcCs|dS)Nr)rrUrrrerrorszErrorHandler.errorcCs|dS)Nr)rrUrrr fatalErrorszErrorHandler.fatalErrorN)rPrQrRrVrWrXrrrrrSsrSc@s\eZdZddZddZddZddZd d Zd d Zd dZ ddZ ddZ ddZ dS)DOMEventStreamcCs2||_||_||_t|jds&|j|_|jdS)Nfeed)streamparserbufsizer#_slurpgetEventreset)rr[r\r]rrrrs  zDOMEventStream.__init__cCs.t|_|jjtjjjd|jj|jdS)Nr ) r pulldomr\Z setFeaturer saxZhandlerZfeature_namespacesZsetContentHandler)rrrrr`szDOMEventStream.resetcCs|j}|r|StdS)N)r_ IndexError)rposrcrrr __getitem__szDOMEventStream.__getitem__cCs|j}|r|StdS)N)r_ StopIteration)rrerrr__next__szDOMEventStream.__next__cCs|S)Nr)rrrr__iter__szDOMEventStream.__iter__cCsp|j}|g}x\|rj|\}}||kr(dS|tkr>|dj||tkrR|j|n|tkr`|d=|j}qWdS)Nr rr)r_r appendChildrr)rr6r>parentstokenZcur_noderrr expandNodes zDOMEventStream.expandNodecCs|jjds|jj|j_x<|jjdsT|jj|j}|sF|jjdS|jj|qW|jjdd}|jjdd|jjd<|S)Nr r) rarrr[readr]r\closerZ)rbufrerrrr_s   zDOMEventStream.getEventcCs|jj|j|j|_|jS)z Fallback replacement for getEvent() using the standard SAX2 interface, which means we slurp the SAX events into memory (no performance gain, but we are compatible to all SAX parsers). )r\parser[_emitr_)rrrrr^szDOMEventStream._slurpcCs,|jjdd}|jjdd|jjd<|S)zn Fallback replacement for getEvent() that emits the events that _slurp() read previously. r r)rar)rrerrrrrszDOMEventStream._emitcCs|jj|`d|_d|_dS)z+clear(): Explicitly release parsing objectsN)rarOr\r[)rrrrrOs zDOMEventStream.clearN) rPrQrRrr`rfrhrirmr_r^rrrOrrrrrYs rYc@s4eZdZddZddZddZddZd d Zd S) SAX2DOMcCs2tj|||||jd}|jd}|j|dS)Nr r)r r8rrj)rr2r3r4curNode parentNoderrrr8#s  zSAX2DOM.startElementNScCs0tj||||jd}|jd}|j|dS)Nr rtrru)r r:rrj)rr2r4rvrwrrrr:)s  zSAX2DOM.startElementcCs4tj||||jdd}|jd}|j|dS)Nrr r)r rCrrrj)rrArBr6rwrrrrC/s zSAX2DOM.processingInstructioncCs2tj|||jdd}|jd}|j|dS)Nrr r)r rFrrrj)rrEr6rwrrrrF5s  zSAX2DOM.ignorableWhitespacecCs2tj|||jdd}|jd}|j|dS)Nrr r)r rGrrrj)rrEr6rwrrrrG;s  zSAX2DOM.charactersN)rPrQrRr8r:rCrFrGrrrrrs!s rsrtcCs@|dkr t}t|tr"t|d}n|}|s4tjj}t|||S)Nrb)default_bufsize isinstancestropenr rb make_parserrY)Zstream_or_stringr\r]r[rrrrqDs   rqcCs6ddlm}t|}||}|s*tjj}t|||S)Nr)StringIO)iorlenr rbrrY)stringr\rr]rprrr parseStringOs   ri@i?)NN)N)Zxml.saxr Zxml.sax.handlerrrrrrrrr rbZContentHandlerr rSrYrsr{rqrrrrrs"8U! __pycache__/pulldom.cpython-36.opt-2.pyc000064400000023567147204745200014040 0ustar003 \-@sddlZddlZdZdZdZdZdZdZdZ d Z Gd d d ej j Z Gd d d ZGdddZGddde ZdZdddZdddZdS)N START_ELEMENT END_ELEMENTCOMMENTSTART_DOCUMENT END_DOCUMENTPROCESSING_INSTRUCTIONIGNORABLE_WHITESPACE CHARACTERSc@seZdZdZdZd$ddZddZddZdd Zd d Z d d Z ddZ ddZ ddZ ddZddZddZddZddZddZd d!Zd"d#ZdS)%PullDOMNc Cszddlm}||_ddg|_|j|_g|_|jj|_y|jj|_Wnt k rVYnX|dig|_ |j d|_ g|_ dS)Nr) XML_NAMESPACExml) Zxml.domr documentFactory firstEvent lastEvent elementStackappendpushpopAttributeError _ns_contexts_current_contextpending_events)selfrr r'/usr/lib64/python3.6/xml/dom/pulldom.py__init__s     zPullDOM.__init__cCs|jd}|jd=|S)Nr rr)r)rresultrrrr!s z PullDOM.popcCs ||_dS)N)_locator)rZlocatorrrrsetDocumentLocator&szPullDOM.setDocumentLocatorcCsHt|dsg|_|jj|pd|f|jj|jj|px|D]\}}||j||f<qWg|_|\}} |r|dkrr|j|} | rn| d| }n| }|jr|jj||} q|j||} n |jr|jj| } n |jd| } x|jD]\}}|\} } | |kr | dkr| }nd| }|jj | |}| j |nX| rL|j| } | r.| d| }n| }|jj | |}| j |n|jj | }| j |||_ qWt| fdg|jd<|jd|_|j| dS)Nzhttp://www.w3.org/2000/xmlns/r!:r"zxmlns:r )getattrZ_attrsr!rdocumentZcreateElementNS buildDocument createElementitemsZcreateAttributeNSZsetAttributeNodeNScreateAttributesetAttributeNodevaluerrr)rnametagNameattrsZ xmlns_uriZ xmlns_attrsanamer1r&Z localnamer%nodeZa_uriZ a_localnameZqnameattrrrrstartElementNS3sP           zPullDOM.startElementNScCs&t|jfdg|jd<|jd|_dS)Nr )rrr)rr2r3rrr endElementNSlszPullDOM.endElementNScCs~|jr|jj|}n |jd|}x0|jD]$\}}|jj|}||_|j|q*Wt|fdg|jd<|jd|_|j |dS)Nr ) r+r-r,r.r/r1r0rrr)rr2r4r6r5r1r7rrr startElementps   zPullDOM.startElementcCs&t|jfdg|jd<|jd|_dS)Nr )rrr)rr2rrr endElementszPullDOM.endElementcCsN|jr2|jj|}t|fdg|jd<|jd|_nt|fdg}|jj|dS)Nr )r+ createCommentrrrr)rsr6eventrrrcomments   zPullDOM.commentcCsR|jr4|jj||}t|fdg|jd<|jd|_nt||fdg}|jj|dS)Nr )r+createProcessingInstructionrrrr)rtargetdatar6r>rrrprocessingInstructions zPullDOM.processingInstructioncCs.|jj|}t|fdg|jd<|jd|_dS)Nr )r+createTextNoderr)rcharsr6rrrignorableWhitespaces zPullDOM.ignorableWhitespacecCs.|jj|}t|fdg|jd<|jd|_dS)Nr )r+rDr r)rrEr6rrr characterss zPullDOM.characterscCs$|jdkr ddl}|jjjj|_dS)Nr)rZxml.dom.minidomZdomZminidomZDocumentimplementation)rr rrr startDocuments zPullDOM.startDocumentc Cs|jj||d}||_t|fdg|jd<|jd|_|j|x|jD]}|ddtkr|d\}}}|jj||}t|f|d<nD|ddt kr|jj |dd}t |f|d<nt d|dd||jd<||_qFWd|_|j S)Nr rzUnknown pending event ) rZcreateDocumentr+rrrrrr@rr<AssertionErrorZ firstChild) rr&Ztagnamer6e_rArBnrrrr,s$     zPullDOM.buildDocumentcCs t|jfdg|jd<|jdS)Nr )rr+rr)rrrr endDocumentszPullDOM.endDocumentcCs d|_dS)N)r+)rrrrclearsz PullDOM.clear)N)__name__ __module__ __qualname__rr+rrr r'r(r8r9r:r;r?rCrFrGrIr,rNrOrrrrr s& 9  r c@s$eZdZddZddZddZdS) ErrorHandlercCs t|dS)N)print)r exceptionrrrwarningszErrorHandler.warningcCs|dS)Nr)rrUrrrerrorszErrorHandler.errorcCs|dS)Nr)rrUrrr fatalErrorszErrorHandler.fatalErrorN)rPrQrRrVrWrXrrrrrSsrSc@s\eZdZddZddZddZddZd d Zd d Zd dZ ddZ ddZ ddZ dS)DOMEventStreamcCs2||_||_||_t|jds&|j|_|jdS)Nfeed)streamparserbufsizer#_slurpgetEventreset)rr[r\r]rrrrs  zDOMEventStream.__init__cCs.t|_|jjtjjjd|jj|jdS)Nr ) r pulldomr\Z setFeaturer saxZhandlerZfeature_namespacesZsetContentHandler)rrrrr`szDOMEventStream.resetcCs|j}|r|StdS)N)r_ IndexError)rposrcrrr __getitem__szDOMEventStream.__getitem__cCs|j}|r|StdS)N)r_ StopIteration)rrerrr__next__szDOMEventStream.__next__cCs|S)Nr)rrrr__iter__szDOMEventStream.__iter__cCsp|j}|g}x\|rj|\}}||kr(dS|tkr>|dj||tkrR|j|n|tkr`|d=|j}qWdS)Nr rr)r_r appendChildrr)rr6r>parentstokenZcur_noderrr expandNodes zDOMEventStream.expandNodecCs|jjds|jj|j_x<|jjdsT|jj|j}|sF|jjdS|jj|qW|jjdd}|jjdd|jjd<|S)Nr r) rarrr[readr]r\closerZ)rbufrerrrr_s   zDOMEventStream.getEventcCs|jj|j|j|_|jS)N)r\parser[_emitr_)rrrrr^szDOMEventStream._slurpcCs,|jjdd}|jjdd|jjd<|S)Nr r)rar)rrerrrrrszDOMEventStream._emitcCs|jj|`d|_d|_dS)N)rarOr\r[)rrrrrOs zDOMEventStream.clearN) rPrQrRrr`rfrhrirmr_r^rrrOrrrrrYs rYc@s4eZdZddZddZddZddZd d Zd S) SAX2DOMcCs2tj|||||jd}|jd}|j|dS)Nr r)r r8rrj)rr2r3r4curNode parentNoderrrr8#s  zSAX2DOM.startElementNScCs0tj||||jd}|jd}|j|dS)Nr rtrru)r r:rrj)rr2r4rvrwrrrr:)s  zSAX2DOM.startElementcCs4tj||||jdd}|jd}|j|dS)Nrr r)r rCrrrj)rrArBr6rwrrrrC/s zSAX2DOM.processingInstructioncCs2tj|||jdd}|jd}|j|dS)Nrr r)r rFrrrj)rrEr6rwrrrrF5s  zSAX2DOM.ignorableWhitespacecCs2tj|||jdd}|jd}|j|dS)Nrr r)r rGrrrj)rrEr6rwrrrrG;s  zSAX2DOM.charactersN)rPrQrRr8r:rCrFrGrrrrrs!s rsrtcCs@|dkr t}t|tr"t|d}n|}|s4tjj}t|||S)Nrb)default_bufsize isinstancestropenr rb make_parserrY)Zstream_or_stringr\r]r[rrrrqDs   rqcCs6ddlm}t|}||}|s*tjj}t|||S)Nr)StringIO)iorlenr rbrrY)stringr\rr]rprrr parseStringOs   ri@i?)NN)N)Zxml.saxr Zxml.sax.handlerrrrrrrrr rbZContentHandlerr rSrYrsr{rqrrrrrs"8U! __pycache__/pulldom.cpython-36.pyc000064400000024451147204745200013071 0ustar003 \-@sddlZddlZdZdZdZdZdZdZdZ d Z Gd d d ej j Z Gd d d ZGdddZGddde ZdZdddZdddZdS)N START_ELEMENT END_ELEMENTCOMMENTSTART_DOCUMENT END_DOCUMENTPROCESSING_INSTRUCTIONIGNORABLE_WHITESPACE CHARACTERSc@seZdZdZdZd$ddZddZddZdd Zd d Z d d Z ddZ ddZ ddZ ddZddZddZddZddZddZd d!Zd"d#ZdS)%PullDOMNc Cszddlm}||_ddg|_|j|_g|_|jj|_y|jj|_Wnt k rVYnX|dig|_ |j d|_ g|_ dS)Nr) XML_NAMESPACExml) Zxml.domr documentFactory firstEvent lastEvent elementStackappendpushpopAttributeError _ns_contexts_current_contextpending_events)selfrr r'/usr/lib64/python3.6/xml/dom/pulldom.py__init__s     zPullDOM.__init__cCs|jd}|jd=|S)Nr rr)r)rresultrrrr!s z PullDOM.popcCs ||_dS)N)_locator)rZlocatorrrrsetDocumentLocator&szPullDOM.setDocumentLocatorcCsHt|dsg|_|jj|pd|f|jj|jj|px|D]\}}||j||f<qWg|_|\}} |r|dkrr|j|} | rn| d| }n| }|jr|jj||} q|j||} n |jr|jj| } n |jd| } x|jD]\}}|\} } | |kr | dkr| }nd| }|jj | |}| j |nX| rL|j| } | r.| d| }n| }|jj | |}| j |n|jj | }| j |||_ qWt| fdg|jd<|jd|_|j| dS)Nzhttp://www.w3.org/2000/xmlns/r!:r"zxmlns:r )getattr_attrsr!rdocumentZcreateElementNS buildDocument createElementitemsZcreateAttributeNSZsetAttributeNodeNScreateAttributesetAttributeNodevaluerrr)rnametagNameattrsZ xmlns_uriZ xmlns_attrsanamer2r&Z localnamer%nodeZa_uriZ a_localnameZqnameattrrrrstartElementNS3sP           zPullDOM.startElementNScCs&t|jfdg|jd<|jd|_dS)Nr )rrr)rr3r4rrr endElementNSlszPullDOM.endElementNScCs~|jr|jj|}n |jd|}x0|jD]$\}}|jj|}||_|j|q*Wt|fdg|jd<|jd|_|j |dS)Nr ) r,r.r-r/r0r2r1rrr)rr3r5r7r6r2r8rrr startElementps   zPullDOM.startElementcCs&t|jfdg|jd<|jd|_dS)Nr )rrr)rr3rrr endElementszPullDOM.endElementcCsN|jr2|jj|}t|fdg|jd<|jd|_nt|fdg}|jj|dS)Nr )r, createCommentrrrr)rsr7eventrrrcomments   zPullDOM.commentcCsR|jr4|jj||}t|fdg|jd<|jd|_nt||fdg}|jj|dS)Nr )r,createProcessingInstructionrrrr)rtargetdatar7r?rrrprocessingInstructions zPullDOM.processingInstructioncCs.|jj|}t|fdg|jd<|jd|_dS)Nr )r,createTextNoderr)rcharsr7rrrignorableWhitespaces zPullDOM.ignorableWhitespacecCs.|jj|}t|fdg|jd<|jd|_dS)Nr )r,rEr r)rrFr7rrr characterss zPullDOM.characterscCs$|jdkr ddl}|jjjj|_dS)Nr)rZxml.dom.minidomZdomZminidomZDocumentimplementation)rr rrr startDocuments zPullDOM.startDocumentc Cs|jj||d}||_t|fdg|jd<|jd|_|j|x|jD]}|ddtkr|d\}}}|jj||}t|f|d<nD|ddt kr|jj |dd}t |f|d<nt d|dd||jd<||_qFWd|_|j S)Nr rzUnknown pending event ) rZcreateDocumentr,rrrrrrArr=AssertionErrorZ firstChild) rr&Ztagnamer7e_rBrCnrrrr-s$     zPullDOM.buildDocumentcCs t|jfdg|jd<|jdS)Nr )rr,rr)rrrr endDocumentszPullDOM.endDocumentcCs d|_dS)z.clear(): Explicitly release parsing structuresN)r,)rrrrclearsz PullDOM.clear)N)__name__ __module__ __qualname__rr,rrr r'r(r9r:r;r<r@rDrGrHrJr-rOrPrrrrr s& 9  r c@s$eZdZddZddZddZdS) ErrorHandlercCs t|dS)N)print)r exceptionrrrwarningszErrorHandler.warningcCs|dS)Nr)rrVrrrerrorszErrorHandler.errorcCs|dS)Nr)rrVrrr fatalErrorszErrorHandler.fatalErrorN)rQrRrSrWrXrYrrrrrTsrTc@s\eZdZddZddZddZddZd d Zd d Zd dZ ddZ ddZ ddZ dS)DOMEventStreamcCs2||_||_||_t|jds&|j|_|jdS)Nfeed)streamparserbufsizer#_slurpgetEventreset)rr\r]r^rrrrs  zDOMEventStream.__init__cCs.t|_|jjtjjjd|jj|jdS)Nr ) r pulldomr]Z setFeaturer saxZhandlerZfeature_namespacesZsetContentHandler)rrrrraszDOMEventStream.resetcCs|j}|r|StdS)N)r` IndexError)rposrcrrr __getitem__szDOMEventStream.__getitem__cCs|j}|r|StdS)N)r` StopIteration)rrfrrr__next__szDOMEventStream.__next__cCs|S)Nr)rrrr__iter__szDOMEventStream.__iter__cCsp|j}|g}x\|rj|\}}||kr(dS|tkr>|dj||tkrR|j|n|tkr`|d=|j}qWdS)Nr rr)r`r appendChildrr)rr7r?parentstokenZcur_noderrr expandNodes zDOMEventStream.expandNodecCs|jjds|jj|j_x<|jjdsT|jj|j}|sF|jjdS|jj|qW|jjdd}|jjdd|jjd<|S)Nr r) rbrrr\readr^r]closer[)rbufrfrrrr`s   zDOMEventStream.getEventcCs|jj|j|j|_|jS)z Fallback replacement for getEvent() using the standard SAX2 interface, which means we slurp the SAX events into memory (no performance gain, but we are compatible to all SAX parsers). )r]parser\_emitr`)rrrrr_szDOMEventStream._slurpcCs,|jjdd}|jjdd|jjd<|S)zn Fallback replacement for getEvent() that emits the events that _slurp() read previously. r r)rbr)rrfrrrrsszDOMEventStream._emitcCs|jj|`d|_d|_dS)z+clear(): Explicitly release parsing objectsN)rbrPr]r\)rrrrrPs zDOMEventStream.clearN) rQrRrSrrargrirjrnr`r_rsrPrrrrrZs rZc@s4eZdZddZddZddZddZd d Zd S) SAX2DOMcCs2tj|||||jd}|jd}|j|dS)Nr r)r r9rrk)rr3r4r5curNode parentNoderrrr9#s  zSAX2DOM.startElementNScCs0tj||||jd}|jd}|j|dS)Nr rurrv)r r;rrk)rr3r5rwrxrrrr;)s  zSAX2DOM.startElementcCs4tj||||jdd}|jd}|j|dS)Nrr r)r rDrrrk)rrBrCr7rxrrrrD/s zSAX2DOM.processingInstructioncCs2tj|||jdd}|jd}|j|dS)Nrr r)r rGrrrk)rrFr7rxrrrrG5s  zSAX2DOM.ignorableWhitespacecCs2tj|||jdd}|jd}|j|dS)Nrr r)r rHrrrk)rrFr7rxrrrrH;s  zSAX2DOM.charactersN)rQrRrSr9r;rDrGrHrrrrrt!s rtrucCs@|dkr t}t|tr"t|d}n|}|s4tjj}t|||S)Nrb)default_bufsize isinstancestropenr rc make_parserrZ)Zstream_or_stringr]r^r\rrrrrDs   rrcCs6ddlm}t|}||}|s*tjj}t|||S)Nr)StringIO)iorlenr rcrrZ)stringr]rr^rqrrr parseStringOs   ri@i?)NN)N)Zxml.saxr Zxml.sax.handlerrrrrrrrr rcZContentHandlerr rTrZrtr|rrrrrrrs"8U! __pycache__/xmlbuilder.cpython-36.opt-1.pyc000064400000032323147204745200014520 0ustar003 \2@sdZddlZddlZddlZddlmZdddgZGdddZGd ddZ d d Z Gd dde Z Gd dde Z GdddZ[GdddZGdddZ[GdddZdS)z4Implementation of the DOM Level 3 'LS-Load' feature.N) NodeFilter DOMBuilderDOMEntityResolverDOMInputSourcec@s\eZdZdZdZdZdZdZdZdZ dZ dZ dZ dZ dZdZdZdZdZdZdZdZdZdS)OptionszFeatures object that has variables set for each DOMBuilder feature. The DOMBuilder class uses an instance of this class to pass settings to the ExpatBuilder class. TFN)__name__ __module__ __qualname____doc__ namespacesnamespace_declarations validationexternal_parameter_entitiesexternal_general_entitiesZexternal_dtd_subsetvalidate_if_schemaZvalidatedatatype_normalizationcreate_entity_ref_nodesentitieswhitespace_in_element_contentcdata_sectionscommentscharset_overrides_xml_encodinginfosetsupported_mediatypes_only errorHandlerfilterrr*/usr/lib64/python3.6/xml/dom/xmlbuilder.pyr s(rc5@sVeZdZdZdZdZdZdZdZdZ eeee fZ ddZ dd Z d d Z d d ZddZddZddZddZddZddZd4d5gd6d7gd8d9gd:d;gdd?gd@dAgdBdCgdDdEgdFdGgdHdIdJgdKdLgdMdNgdOdPgdQdRgdSdTgdUdVgdWdXgdYdZgd[d\gd]gd^d_d`dadbdcdddedfdgg dhdigdjdkgdldmgiZd*d+Zd,d-Zd.d/Zd0d1Zd2d3ZdS)nrNrcCs t|_dS)N)r_options)selfrrr__init__:szDOMBuilder.__init__cCs|jS)N)entityResolver)r#rrr_get_entityResolver=szDOMBuilder._get_entityResolvercCs ||_dS)N)r%)r#r%rrr_set_entityResolver?szDOMBuilder._set_entityResolvercCs|jS)N)r)r#rrr_get_errorHandlerBszDOMBuilder._get_errorHandlercCs ||_dS)N)r)r#rrrr_set_errorHandlerDszDOMBuilder._set_errorHandlercCs|jS)N)r)r#rrr _get_filterGszDOMBuilder._get_filtercCs ||_dS)N)r)r#rrrr _set_filterIszDOMBuilder._set_filterc Cs|j|rv|rdpd}y|jt||f}Wn&tk rRtjjd|fYqXx4|D]\}}t|j||qZWntjj dt |dS)Nrrzunsupported feature: %rzunknown feature: ) supportsFeature _settings _name_xformKeyErrorxmldomNotSupportedErrsetattrr" NotFoundErrrepr)r#namestateZsettingsvaluerrr setFeatureLs  zDOMBuilder.setFeaturecCst|jt|S)N)hasattrr"r.)r#r6rrrr,ZszDOMBuilder.supportsFeaturecCst||rdpdf}||jkS)Nrr)r.r-)r#r6r7keyrrr canSetFeature]szDOMBuilder.canSetFeaturer rrrrrrrrrrrrrrr c Cst|}y t|j|Stk r|dkrj|j}|joh|joh|joh|joh|jpf|j pf|j pf|j pf|j St jjdt|YnXdS)Nrzfeature %s not known)r.getattrr"AttributeErrorrrrrr rrrrr0r1r4r5)r#r6Zxnameoptionsrrr getFeatures  zDOMBuilder.getFeaturecCs.|jr|jjd|}ntjd|}|j|S)N)r% resolveEntityrparse)r#uriinputrrrparseURIszDOMBuilder.parseURIcCsRtj|j}|j|_|j|_|j}|dkrF|jrFddl}|jj|j}|j ||S)Nr) copyr"rr byteStreamsystemIdurllib.requestrequestZurlopen_parse_bytestream)r#rDr?fpurllibrrrrBs zDOMBuilder.parsecCs||jkrtdtddS)Nznot a legal actionzHaven't written this yet...)_legal_actions ValueErrorNotImplementedError)r#rDZcnodeactionrrrparseWithContexts zDOMBuilder.parseWithContextcCs ddl}|jjj|}|j|S)Nr)Zxml.dom.expatbuilderr1Z expatbuilderZ makeBuilderZ parseFile)r#streamr?r0ZbuilderrrrrKszDOMBuilder._parse_bytestream)r r)r r)r r)r r)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)r r)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)r r)r r)r r)r r)rr r r%rrZACTION_REPLACEZACTION_APPEND_AS_CHILDRENZACTION_INSERT_AFTERZACTION_INSERT_BEFORErNr$r&r'r(r)r*r+r9r,r<r-r@rErBrRrKrrrrr-s  cCs|jjddS)N-_)lowerreplace)r6rrrr.sr.c@s0eZdZd ZddZddZddZdd Zd S) r_openerc Cst}||_||_|jj||_|j||_ddl}ddl }|j j |}|\}}} } } } | r| j d r|j | d} ||| | | | f}|j j||_|S)Nr/)rpublicIdrH _get_openeropenrG_guess_media_encodingencoding posixpathZ urllib.parserBZurlparseendswithdirnameZ urlunparsebaseURI) r#rZrHsourcer_rMpartsschemeZnetlocpathZparamsZqueryZfragmentrrrrAs  zDOMEntityResolver.resolveEntityc Cs,y|jStk r&|j|_|jSXdS)N)rXr>_create_opener)r#rrrr[s  zDOMEntityResolver._get_openercCsddl}|jjS)Nr)rIrJZ build_opener)r#rMrrrrgsz DOMEntityResolver._create_openercCsF|jj}d|krBx.|jD]"}|jdr|jdddjSqWdS)Nz Content-Typezcharset==r)rGinfoZgetplist startswithsplitrV)r#rcriZparamrrrr]s   z'DOMEntityResolver._guess_media_encodingN)rX)rr r __slots__rAr[rgr]rrrrrs c@seZdZd'Zdd Zd d Zd d ZddZddZddZ ddZ ddZ ddZ ddZ ddZddZd d!Zd"d#Zd$d%Zd&S)(rrGcharacterStream stringDatar^rZrHrbcCs.d|_d|_d|_d|_d|_d|_d|_dS)N)rGrmrnr^rZrHrb)r#rrrr$szDOMInputSource.__init__cCs|jS)N)rG)r#rrr_get_byteStreamszDOMInputSource._get_byteStreamcCs ||_dS)N)rG)r#rGrrr_set_byteStreamszDOMInputSource._set_byteStreamcCs|jS)N)rm)r#rrr_get_characterStreamsz#DOMInputSource._get_characterStreamcCs ||_dS)N)rm)r#rmrrr_set_characterStreamsz#DOMInputSource._set_characterStreamcCs|jS)N)rn)r#rrr_get_stringDataszDOMInputSource._get_stringDatacCs ||_dS)N)rn)r#datarrr_set_stringDataszDOMInputSource._set_stringDatacCs|jS)N)r^)r#rrr _get_encodingszDOMInputSource._get_encodingcCs ||_dS)N)r^)r#r^rrr _set_encodingszDOMInputSource._set_encodingcCs|jS)N)rZ)r#rrr _get_publicId"szDOMInputSource._get_publicIdcCs ||_dS)N)rZ)r#rZrrr _set_publicId$szDOMInputSource._set_publicIdcCs|jS)N)rH)r#rrr _get_systemId'szDOMInputSource._get_systemIdcCs ||_dS)N)rH)r#rHrrr _set_systemId)szDOMInputSource._set_systemIdcCs|jS)N)rb)r#rrr _get_baseURI,szDOMInputSource._get_baseURIcCs ||_dS)N)rb)r#rCrrr _set_baseURI.szDOMInputSource._set_baseURIN)rGrmrnr^rZrHrb)rr r rlr$rorprqrrrsrurvrwrxryrzr{r|r}rrrrrs" c@s>eZdZdZdZdZdZdZej Z ddZ dd Z d d Z d S) DOMBuilderFilterzSElement filter which can be used to tailor construction of a DOM instance. rrr r!cCs|jS)N) whatToShow)r#rrr_get_whatToShowCsz DOMBuilderFilter._get_whatToShowcCs|jS)N) FILTER_ACCEPT)r#elementrrr acceptNodeFszDOMBuilderFilter.acceptNodecCs|jS)N)r)r#rrrrstartContainerIszDOMBuilderFilter.startContainerN)rr r r rZ FILTER_REJECTZ FILTER_SKIPZFILTER_INTERRUPTrZSHOW_ALLrrrrrrrrr~2sr~c@s$eZdZddZddZddZdS)_AsyncDeprecatedPropertycCs|j}tjdj|dtdS)Nz+{cls}.async is deprecated; use {cls}.async_)cls)rwarningswarnformatDeprecationWarning)r#rZclsnamerrrrPs z_AsyncDeprecatedProperty.warncCs|j||dk r|jSdS)NF)rasync_)r#instancerrrr__get__Vs z _AsyncDeprecatedProperty.__get__cCs|jt|t|d|dS)Nr)rtyper3)r#rr8rrr__set__\sz _AsyncDeprecatedProperty.__set__N)rr r rrrrrrrrOsrc@sPeZdZdZdZeed<ddZddZdd Z d d Z d d Z ddZ dS) DocumentLSz=Mixin to create documents that conform to the load/save spec.FasynccCsdS)NFr)r#rrr _get_asyncgszDocumentLS._get_asynccCs|rtjjddS)Nz.asynchronous document loading is not supported)r0r1r2)r#flagrrr _set_asyncjszDocumentLS._set_asynccCs tddS)Nz'haven't figured out what this means yet)rP)r#rrrabortoszDocumentLS.abortcCs tddS)Nzhaven't written this yet)rP)r#rCrrrloaduszDocumentLS.loadcCs tddS)Nzhaven't written this yet)rP)r#rcrrrloadXMLxszDocumentLS.loadXMLcCs*|dkr|}n|j|k r"tjj|jS)N)Z ownerDocumentr0r1ZWrongDocumentErrZtoxml)r#ZsnoderrrsaveXML{s   zDocumentLS.saveXMLN) rr r r rrlocalsrrrrrrrrrrras rc@s,eZdZdZdZddZddZddZd S) DOMImplementationLSrrcCsF|dk rtjjd||jkr$tS||jkr:tjjdtddS)NzschemaType not yet supportedz'asynchronous builders are not supportedzunknown value for mode)r0r1r2MODE_SYNCHRONOUSrMODE_ASYNCHRONOUSrO)r#modeZ schemaTyperrrcreateDOMBuilders  z$DOMImplementationLS.createDOMBuildercCs tddS)Nz-the writer interface hasn't been written yet!)rP)r#rrrcreateDOMWritersz#DOMImplementationLS.createDOMWritercCstS)N)r)r#rrrcreateDOMInputSourcesz(DOMImplementationLS.createDOMInputSourceN)rr r rrrrrrrrrrs  r)r rFrZxml.domr0Zxml.dom.NodeFilterr__all__rrr.objectrrr~rrrrrrrs"   %,1"__pycache__/xmlbuilder.cpython-36.opt-2.pyc000064400000031446147204745200014526 0ustar003 \2@sddlZddlZddlZddlmZdddgZGdddZGdddZd d Z Gd dde Z Gd dde Z Gd ddZ [GdddZGdddZ[GdddZdS)N) NodeFilter DOMBuilderDOMEntityResolverDOMInputSourcec@sXeZdZdZdZdZdZdZdZdZ dZ dZ dZ dZ dZdZdZdZdZdZdZdZdS)OptionsTFN)__name__ __module__ __qualname__ namespacesnamespace_declarations validationexternal_parameter_entitiesexternal_general_entitiesZexternal_dtd_subsetvalidate_if_schemaZvalidatedatatype_normalizationcreate_entity_ref_nodesentitieswhitespace_in_element_contentcdata_sectionscommentscharset_overrides_xml_encodinginfosetsupported_mediatypes_only errorHandlerfilterrr*/usr/lib64/python3.6/xml/dom/xmlbuilder.pyr s& rc5@sVeZdZdZdZdZdZdZdZdZ eeee fZ ddZ dd Z d d Z d d ZddZddZddZddZddZddZd4d5gd6d7gd8d9gd:d;gdd?gd@dAgdBdCgdDdEgdFdGgdHdIdJgdKdLgdMdNgdOdPgdQdRgdSdTgdUdVgdWdXgdYdZgd[d\gd]gd^d_d`dadbdcdddedfdgg dhdigdjdkgdldmgiZd*d+Zd,d-Zd.d/Zd0d1Zd2d3ZdS)nrNrcCs t|_dS)N)r_options)selfrrr__init__:szDOMBuilder.__init__cCs|jS)N)entityResolver)r"rrr_get_entityResolver=szDOMBuilder._get_entityResolvercCs ||_dS)N)r$)r"r$rrr_set_entityResolver?szDOMBuilder._set_entityResolvercCs|jS)N)r)r"rrr_get_errorHandlerBszDOMBuilder._get_errorHandlercCs ||_dS)N)r)r"rrrr_set_errorHandlerDszDOMBuilder._set_errorHandlercCs|jS)N)r)r"rrr _get_filterGszDOMBuilder._get_filtercCs ||_dS)N)r)r"rrrr _set_filterIszDOMBuilder._set_filterc Cs|j|rv|rdpd}y|jt||f}Wn&tk rRtjjd|fYqXx4|D]\}}t|j||qZWntjj dt |dS)Nrrzunsupported feature: %rzunknown feature: ) supportsFeature _settings _name_xformKeyErrorxmldomNotSupportedErrsetattrr! NotFoundErrrepr)r"namestateZsettingsvaluerrr setFeatureLs  zDOMBuilder.setFeaturecCst|jt|S)N)hasattrr!r-)r"r5rrrr+ZszDOMBuilder.supportsFeaturecCst||rdpdf}||jkS)Nrr)r-r,)r"r5r6keyrrr canSetFeature]szDOMBuilder.canSetFeaturer rr rrrrrrrrrrrrr c Cst|}y t|j|Stk r|dkrj|j}|joh|joh|joh|joh|jpf|j pf|j pf|j pf|j St jjdt|YnXdS)Nrzfeature %s not known)r-getattrr!AttributeErrorrrrrr rrrrr/r0r3r4)r"r5Zxnameoptionsrrr getFeatures  zDOMBuilder.getFeaturecCs.|jr|jjd|}ntjd|}|j|S)N)r$ resolveEntityrparse)r"uriinputrrrparseURIszDOMBuilder.parseURIcCsRtj|j}|j|_|j|_|j}|dkrF|jrFddl}|jj|j}|j ||S)Nr) copyr!rr byteStreamsystemIdurllib.requestrequestZurlopen_parse_bytestream)r"rCr>fpurllibrrrrAs zDOMBuilder.parsecCs||jkrtdtddS)Nznot a legal actionzHaven't written this yet...)_legal_actions ValueErrorNotImplementedError)r"rCZcnodeactionrrrparseWithContexts zDOMBuilder.parseWithContextcCs ddl}|jjj|}|j|S)Nr)Zxml.dom.expatbuilderr0Z expatbuilderZ makeBuilderZ parseFile)r"streamr>r/ZbuilderrrrrJszDOMBuilder._parse_bytestream)r r)r r)r r)r r)r r)r r)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)r r)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)r r)r r)r r)r r)rr r r$rrZACTION_REPLACEZACTION_APPEND_AS_CHILDRENZACTION_INSERT_AFTERZACTION_INSERT_BEFORErMr#r%r&r'r(r)r*r8r+r;r,r?rDrArQrJrrrrr-s  cCs|jjddS)N-_)lowerreplace)r5rrrr-sr-c@s0eZdZd ZddZddZddZdd Zd S) r_openerc Cst}||_||_|jj||_|j||_ddl}ddl }|j j |}|\}}} } } } | r| j d r|j | d} ||| | | | f}|j j||_|S)Nr/)rpublicIdrG _get_openeropenrF_guess_media_encodingencoding posixpathZ urllib.parserAZurlparseendswithdirnameZ urlunparsebaseURI) r"rYrGsourcer^rLpartsschemeZnetlocpathZparamsZqueryZfragmentrrrr@s  zDOMEntityResolver.resolveEntityc Cs,y|jStk r&|j|_|jSXdS)N)rWr=_create_opener)r"rrrrZs  zDOMEntityResolver._get_openercCsddl}|jjS)Nr)rHrIZ build_opener)r"rLrrrrfsz DOMEntityResolver._create_openercCsF|jj}d|krBx.|jD]"}|jdr|jdddjSqWdS)Nz Content-Typezcharset==r)rFinfoZgetplist startswithsplitrU)r"rbrhZparamrrrr\s   z'DOMEntityResolver._guess_media_encodingN)rW)rr r __slots__r@rZrfr\rrrrrs c@seZdZd'Zdd Zd d Zd d ZddZddZddZ ddZ ddZ ddZ ddZ ddZddZd d!Zd"d#Zd$d%Zd&S)(rrFcharacterStream stringDatar]rYrGracCs.d|_d|_d|_d|_d|_d|_d|_dS)N)rFrlrmr]rYrGra)r"rrrr#szDOMInputSource.__init__cCs|jS)N)rF)r"rrr_get_byteStreamszDOMInputSource._get_byteStreamcCs ||_dS)N)rF)r"rFrrr_set_byteStreamszDOMInputSource._set_byteStreamcCs|jS)N)rl)r"rrr_get_characterStreamsz#DOMInputSource._get_characterStreamcCs ||_dS)N)rl)r"rlrrr_set_characterStreamsz#DOMInputSource._set_characterStreamcCs|jS)N)rm)r"rrr_get_stringDataszDOMInputSource._get_stringDatacCs ||_dS)N)rm)r"datarrr_set_stringDataszDOMInputSource._set_stringDatacCs|jS)N)r])r"rrr _get_encodingszDOMInputSource._get_encodingcCs ||_dS)N)r])r"r]rrr _set_encodingszDOMInputSource._set_encodingcCs|jS)N)rY)r"rrr _get_publicId"szDOMInputSource._get_publicIdcCs ||_dS)N)rY)r"rYrrr _set_publicId$szDOMInputSource._set_publicIdcCs|jS)N)rG)r"rrr _get_systemId'szDOMInputSource._get_systemIdcCs ||_dS)N)rG)r"rGrrr _set_systemId)szDOMInputSource._set_systemIdcCs|jS)N)ra)r"rrr _get_baseURI,szDOMInputSource._get_baseURIcCs ||_dS)N)ra)r"rBrrr _set_baseURI.szDOMInputSource._set_baseURIN)rFrlrmr]rYrGra)rr r rkr#rnrorprqrrrtrurvrwrxryrzr{r|rrrrrs" c@s:eZdZdZdZdZdZejZ ddZ ddZ d d Z d S) DOMBuilderFilterrrrr cCs|jS)N) whatToShow)r"rrr_get_whatToShowCsz DOMBuilderFilter._get_whatToShowcCs|jS)N) FILTER_ACCEPT)r"elementrrr acceptNodeFszDOMBuilderFilter.acceptNodecCs|jS)N)r)r"rrrrstartContainerIszDOMBuilderFilter.startContainerN) rr r rZ FILTER_REJECTZ FILTER_SKIPZFILTER_INTERRUPTrZSHOW_ALLr~rrrrrrrr}2s r}c@s$eZdZddZddZddZdS)_AsyncDeprecatedPropertycCs|j}tjdj|dtdS)Nz+{cls}.async is deprecated; use {cls}.async_)cls)rwarningswarnformatDeprecationWarning)r"rZclsnamerrrrPs z_AsyncDeprecatedProperty.warncCs|j||dk r|jSdS)NF)rasync_)r"instancerrrr__get__Vs z _AsyncDeprecatedProperty.__get__cCs|jt|t|d|dS)Nr)rtyper2)r"rr7rrr__set__\sz _AsyncDeprecatedProperty.__set__N)rr r rrrrrrrrOsrc@sLeZdZdZeed<ddZddZddZd d Z d d Z d dZ dS) DocumentLSFasynccCsdS)NFr)r"rrr _get_asyncgszDocumentLS._get_asynccCs|rtjjddS)Nz.asynchronous document loading is not supported)r/r0r1)r"flagrrr _set_asyncjszDocumentLS._set_asynccCs tddS)Nz'haven't figured out what this means yet)rO)r"rrrabortoszDocumentLS.abortcCs tddS)Nzhaven't written this yet)rO)r"rBrrrloaduszDocumentLS.loadcCs tddS)Nzhaven't written this yet)rO)r"rbrrrloadXMLxszDocumentLS.loadXMLcCs*|dkr|}n|j|k r"tjj|jS)N)Z ownerDocumentr/r0ZWrongDocumentErrZtoxml)r"ZsnoderrrsaveXML{s   zDocumentLS.saveXMLN) rr r rrlocalsrrrrrrrrrrras rc@s,eZdZdZdZddZddZddZd S) DOMImplementationLSrrcCsF|dk rtjjd||jkr$tS||jkr:tjjdtddS)NzschemaType not yet supportedz'asynchronous builders are not supportedzunknown value for mode)r/r0r1MODE_SYNCHRONOUSrMODE_ASYNCHRONOUSrN)r"modeZ schemaTyperrrcreateDOMBuilders  z$DOMImplementationLS.createDOMBuildercCs tddS)Nz-the writer interface hasn't been written yet!)rO)r"rrrcreateDOMWritersz#DOMImplementationLS.createDOMWritercCstS)N)r)r"rrrcreateDOMInputSourcesz(DOMImplementationLS.createDOMInputSourceN)rr r rrrrrrrrrrs  r)rErZxml.domr/Zxml.dom.NodeFilterr__all__rrr-objectrrr}rrrrrrrs    %,1"__pycache__/xmlbuilder.cpython-36.pyc000064400000032361147204745200013563 0ustar003 \2@sdZddlZddlZddlZddlmZdddgZGdddZGd ddZ d d Z Gd dde Z Gd dde Z GdddZ[GdddZGdddZ[GdddZdS)z4Implementation of the DOM Level 3 'LS-Load' feature.N) NodeFilter DOMBuilderDOMEntityResolverDOMInputSourcec@s\eZdZdZdZdZdZdZdZdZ dZ dZ dZ dZ dZdZdZdZdZdZdZdZdZdS)OptionszFeatures object that has variables set for each DOMBuilder feature. The DOMBuilder class uses an instance of this class to pass settings to the ExpatBuilder class. TFN)__name__ __module__ __qualname____doc__ namespacesnamespace_declarations validationexternal_parameter_entitiesexternal_general_entitiesZexternal_dtd_subsetvalidate_if_schemaZvalidatedatatype_normalizationcreate_entity_ref_nodesentitieswhitespace_in_element_contentcdata_sectionscommentscharset_overrides_xml_encodinginfosetsupported_mediatypes_only errorHandlerfilterrr*/usr/lib64/python3.6/xml/dom/xmlbuilder.pyr s(rc5@sVeZdZdZdZdZdZdZdZdZ eeee fZ ddZ dd Z d d Z d d ZddZddZddZddZddZddZd4d5gd6d7gd8d9gd:d;gdd?gd@dAgdBdCgdDdEgdFdGgdHdIdJgdKdLgdMdNgdOdPgdQdRgdSdTgdUdVgdWdXgdYdZgd[d\gd]gd^d_d`dadbdcdddedfdgg dhdigdjdkgdldmgiZd*d+Zd,d-Zd.d/Zd0d1Zd2d3ZdS)nrNrcCs t|_dS)N)r_options)selfrrr__init__:szDOMBuilder.__init__cCs|jS)N)entityResolver)r#rrr_get_entityResolver=szDOMBuilder._get_entityResolvercCs ||_dS)N)r%)r#r%rrr_set_entityResolver?szDOMBuilder._set_entityResolvercCs|jS)N)r)r#rrr_get_errorHandlerBszDOMBuilder._get_errorHandlercCs ||_dS)N)r)r#rrrr_set_errorHandlerDszDOMBuilder._set_errorHandlercCs|jS)N)r)r#rrr _get_filterGszDOMBuilder._get_filtercCs ||_dS)N)r)r#rrrr _set_filterIszDOMBuilder._set_filterc Cs|j|rv|rdpd}y|jt||f}Wn&tk rRtjjd|fYqXx4|D]\}}t|j||qZWntjj dt |dS)Nrrzunsupported feature: %rzunknown feature: ) supportsFeature _settings _name_xformKeyErrorxmldomNotSupportedErrsetattrr" NotFoundErrrepr)r#namestateZsettingsvaluerrr setFeatureLs  zDOMBuilder.setFeaturecCst|jt|S)N)hasattrr"r.)r#r6rrrr,ZszDOMBuilder.supportsFeaturecCst||rdpdf}||jkS)Nrr)r.r-)r#r6r7keyrrr canSetFeature]szDOMBuilder.canSetFeaturer rrrrrrrrrrrrrrr c Cst|}y t|j|Stk r|dkrj|j}|joh|joh|joh|joh|jpf|j pf|j pf|j pf|j St jjdt|YnXdS)Nrzfeature %s not known)r.getattrr"AttributeErrorrrrrr rrrrr0r1r4r5)r#r6Zxnameoptionsrrr getFeatures  zDOMBuilder.getFeaturecCs.|jr|jjd|}ntjd|}|j|S)N)r% resolveEntityrparse)r#uriinputrrrparseURIszDOMBuilder.parseURIcCsRtj|j}|j|_|j|_|j}|dkrF|jrFddl}|jj|j}|j ||S)Nr) copyr"rr byteStreamsystemIdurllib.requestrequestZurlopen_parse_bytestream)r#rDr?fpurllibrrrrBs zDOMBuilder.parsecCs||jkrtdtddS)Nznot a legal actionzHaven't written this yet...)_legal_actions ValueErrorNotImplementedError)r#rDZcnodeactionrrrparseWithContexts zDOMBuilder.parseWithContextcCs ddl}|jjj|}|j|S)Nr)Zxml.dom.expatbuilderr1Z expatbuilderZ makeBuilderZ parseFile)r#streamr?r0ZbuilderrrrrKszDOMBuilder._parse_bytestream)r r)r r)r r)r r)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)r r)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)r r)r r)r r)r r)rr r r%rrZACTION_REPLACEZACTION_APPEND_AS_CHILDRENZACTION_INSERT_AFTERZACTION_INSERT_BEFORErNr$r&r'r(r)r*r+r9r,r<r-r@rErBrRrKrrrrr-s  cCs|jjddS)N-_)lowerreplace)r6rrrr.sr.c@s0eZdZd ZddZddZddZdd Zd S) r_openerc Cs|dk s tt}||_||_|jj||_|j||_ddl }ddl }|j j |}|\}}} } } } | r| j d r|j| d} ||| | | | f}|j j||_|S)Nr/)AssertionErrorrpublicIdrH _get_openeropenrG_guess_media_encodingencoding posixpathZ urllib.parserBZurlparseendswithdirnameZ urlunparsebaseURI) r#r[rHsourcer`rMpartsschemeZnetlocpathZparamsZqueryZfragmentrrrrAs   zDOMEntityResolver.resolveEntityc Cs,y|jStk r&|j|_|jSXdS)N)rXr>_create_opener)r#rrrr\s  zDOMEntityResolver._get_openercCsddl}|jjS)Nr)rIrJZ build_opener)r#rMrrrrhsz DOMEntityResolver._create_openercCsF|jj}d|krBx.|jD]"}|jdr|jdddjSqWdS)Nz Content-Typezcharset==r)rGinfoZgetplist startswithsplitrV)r#rdrjZparamrrrr^s   z'DOMEntityResolver._guess_media_encodingN)rX)rr r __slots__rAr\rhr^rrrrrs c@seZdZd'Zdd Zd d Zd d ZddZddZddZ ddZ ddZ ddZ ddZ ddZddZd d!Zd"d#Zd$d%Zd&S)(rrGcharacterStream stringDatar_r[rHrccCs.d|_d|_d|_d|_d|_d|_d|_dS)N)rGrnror_r[rHrc)r#rrrr$szDOMInputSource.__init__cCs|jS)N)rG)r#rrr_get_byteStreamszDOMInputSource._get_byteStreamcCs ||_dS)N)rG)r#rGrrr_set_byteStreamszDOMInputSource._set_byteStreamcCs|jS)N)rn)r#rrr_get_characterStreamsz#DOMInputSource._get_characterStreamcCs ||_dS)N)rn)r#rnrrr_set_characterStreamsz#DOMInputSource._set_characterStreamcCs|jS)N)ro)r#rrr_get_stringDataszDOMInputSource._get_stringDatacCs ||_dS)N)ro)r#datarrr_set_stringDataszDOMInputSource._set_stringDatacCs|jS)N)r_)r#rrr _get_encodingszDOMInputSource._get_encodingcCs ||_dS)N)r_)r#r_rrr _set_encodingszDOMInputSource._set_encodingcCs|jS)N)r[)r#rrr _get_publicId"szDOMInputSource._get_publicIdcCs ||_dS)N)r[)r#r[rrr _set_publicId$szDOMInputSource._set_publicIdcCs|jS)N)rH)r#rrr _get_systemId'szDOMInputSource._get_systemIdcCs ||_dS)N)rH)r#rHrrr _set_systemId)szDOMInputSource._set_systemIdcCs|jS)N)rc)r#rrr _get_baseURI,szDOMInputSource._get_baseURIcCs ||_dS)N)rc)r#rCrrr _set_baseURI.szDOMInputSource._set_baseURIN)rGrnror_r[rHrc)rr r rmr$rprqrrrsrtrvrwrxryrzr{r|r}r~rrrrrs" c@s>eZdZdZdZdZdZdZej Z ddZ dd Z d d Z d S) DOMBuilderFilterzSElement filter which can be used to tailor construction of a DOM instance. rrr r!cCs|jS)N) whatToShow)r#rrr_get_whatToShowCsz DOMBuilderFilter._get_whatToShowcCs|jS)N) FILTER_ACCEPT)r#elementrrr acceptNodeFszDOMBuilderFilter.acceptNodecCs|jS)N)r)r#rrrrstartContainerIszDOMBuilderFilter.startContainerN)rr r r rZ FILTER_REJECTZ FILTER_SKIPZFILTER_INTERRUPTrZSHOW_ALLrrrrrrrrr2src@s$eZdZddZddZddZdS)_AsyncDeprecatedPropertycCs|j}tjdj|dtdS)Nz+{cls}.async is deprecated; use {cls}.async_)cls)rwarningswarnformatDeprecationWarning)r#rZclsnamerrrrPs z_AsyncDeprecatedProperty.warncCs|j||dk r|jSdS)NF)rasync_)r#instancerrrr__get__Vs z _AsyncDeprecatedProperty.__get__cCs|jt|t|d|dS)Nr)rtyper3)r#rr8rrr__set__\sz _AsyncDeprecatedProperty.__set__N)rr r rrrrrrrrOsrc@sPeZdZdZdZeed<ddZddZdd Z d d Z d d Z ddZ dS) DocumentLSz=Mixin to create documents that conform to the load/save spec.FasynccCsdS)NFr)r#rrr _get_asyncgszDocumentLS._get_asynccCs|rtjjddS)Nz.asynchronous document loading is not supported)r0r1r2)r#flagrrr _set_asyncjszDocumentLS._set_asynccCs tddS)Nz'haven't figured out what this means yet)rP)r#rrrabortoszDocumentLS.abortcCs tddS)Nzhaven't written this yet)rP)r#rCrrrloaduszDocumentLS.loadcCs tddS)Nzhaven't written this yet)rP)r#rdrrrloadXMLxszDocumentLS.loadXMLcCs*|dkr|}n|j|k r"tjj|jS)N)Z ownerDocumentr0r1ZWrongDocumentErrZtoxml)r#ZsnoderrrsaveXML{s   zDocumentLS.saveXMLN) rr r r rrlocalsrrrrrrrrrrras rc@s,eZdZdZdZddZddZddZd S) DOMImplementationLSrrcCsF|dk rtjjd||jkr$tS||jkr:tjjdtddS)NzschemaType not yet supportedz'asynchronous builders are not supportedzunknown value for mode)r0r1r2MODE_SYNCHRONOUSrMODE_ASYNCHRONOUSrO)r#modeZ schemaTyperrrcreateDOMBuilders  z$DOMImplementationLS.createDOMBuildercCs tddS)Nz-the writer interface hasn't been written yet!)rP)r#rrrcreateDOMWritersz#DOMImplementationLS.createDOMWritercCstS)N)r)r#rrrcreateDOMInputSourcesz(DOMImplementationLS.createDOMInputSourceN)rr r rrrrrrrrrrs  r)r rFrZxml.domr0Zxml.dom.NodeFilterr__all__rrr.objectrrrrrrrrrrs"   %,1"NodeFilter.py000064400000001650147204745200007160 0ustar00# This is the Python mapping for interface NodeFilter from # DOM2-Traversal-Range. It contains only constants. class NodeFilter: """ This is the DOM2 NodeFilter interface. It contains only constants. """ FILTER_ACCEPT = 1 FILTER_REJECT = 2 FILTER_SKIP = 3 SHOW_ALL = 0xFFFFFFFF SHOW_ELEMENT = 0x00000001 SHOW_ATTRIBUTE = 0x00000002 SHOW_TEXT = 0x00000004 SHOW_CDATA_SECTION = 0x00000008 SHOW_ENTITY_REFERENCE = 0x00000010 SHOW_ENTITY = 0x00000020 SHOW_PROCESSING_INSTRUCTION = 0x00000040 SHOW_COMMENT = 0x00000080 SHOW_DOCUMENT = 0x00000100 SHOW_DOCUMENT_TYPE = 0x00000200 SHOW_DOCUMENT_FRAGMENT = 0x00000400 SHOW_NOTATION = 0x00000800 def acceptNode(self, node): raise NotImplementedError __init__.py000064400000007663147204745200006676 0ustar00"""W3C Document Object Model implementation for Python. The Python mapping of the Document Object Model is documented in the Python Library Reference in the section on the xml.dom package. This package contains the following modules: minidom -- A simple implementation of the Level 1 DOM with namespace support added (based on the Level 2 specification) and other minor Level 2 functionality. pulldom -- DOM builder supporting on-demand tree-building for selected subtrees of the document. """ class Node: """Class giving the NodeType constants.""" __slots__ = () # DOM implementations may use this as a base class for their own # Node implementations. If they don't, the constants defined here # should still be used as the canonical definitions as they match # the values given in the W3C recommendation. Client code can # safely refer to these values in all tests of Node.nodeType # values. ELEMENT_NODE = 1 ATTRIBUTE_NODE = 2 TEXT_NODE = 3 CDATA_SECTION_NODE = 4 ENTITY_REFERENCE_NODE = 5 ENTITY_NODE = 6 PROCESSING_INSTRUCTION_NODE = 7 COMMENT_NODE = 8 DOCUMENT_NODE = 9 DOCUMENT_TYPE_NODE = 10 DOCUMENT_FRAGMENT_NODE = 11 NOTATION_NODE = 12 #ExceptionCode INDEX_SIZE_ERR = 1 DOMSTRING_SIZE_ERR = 2 HIERARCHY_REQUEST_ERR = 3 WRONG_DOCUMENT_ERR = 4 INVALID_CHARACTER_ERR = 5 NO_DATA_ALLOWED_ERR = 6 NO_MODIFICATION_ALLOWED_ERR = 7 NOT_FOUND_ERR = 8 NOT_SUPPORTED_ERR = 9 INUSE_ATTRIBUTE_ERR = 10 INVALID_STATE_ERR = 11 SYNTAX_ERR = 12 INVALID_MODIFICATION_ERR = 13 NAMESPACE_ERR = 14 INVALID_ACCESS_ERR = 15 VALIDATION_ERR = 16 class DOMException(Exception): """Abstract base class for DOM exceptions. Exceptions with specific codes are specializations of this class.""" def __init__(self, *args, **kw): if self.__class__ is DOMException: raise RuntimeError( "DOMException should not be instantiated directly") Exception.__init__(self, *args, **kw) def _get_code(self): return self.code class IndexSizeErr(DOMException): code = INDEX_SIZE_ERR class DomstringSizeErr(DOMException): code = DOMSTRING_SIZE_ERR class HierarchyRequestErr(DOMException): code = HIERARCHY_REQUEST_ERR class WrongDocumentErr(DOMException): code = WRONG_DOCUMENT_ERR class InvalidCharacterErr(DOMException): code = INVALID_CHARACTER_ERR class NoDataAllowedErr(DOMException): code = NO_DATA_ALLOWED_ERR class NoModificationAllowedErr(DOMException): code = NO_MODIFICATION_ALLOWED_ERR class NotFoundErr(DOMException): code = NOT_FOUND_ERR class NotSupportedErr(DOMException): code = NOT_SUPPORTED_ERR class InuseAttributeErr(DOMException): code = INUSE_ATTRIBUTE_ERR class InvalidStateErr(DOMException): code = INVALID_STATE_ERR class SyntaxErr(DOMException): code = SYNTAX_ERR class InvalidModificationErr(DOMException): code = INVALID_MODIFICATION_ERR class NamespaceErr(DOMException): code = NAMESPACE_ERR class InvalidAccessErr(DOMException): code = INVALID_ACCESS_ERR class ValidationErr(DOMException): code = VALIDATION_ERR class UserDataHandler: """Class giving the operation constants for UserDataHandler.handle().""" # Based on DOM Level 3 (WD 9 April 2002) NODE_CLONED = 1 NODE_IMPORTED = 2 NODE_DELETED = 3 NODE_RENAMED = 4 XML_NAMESPACE = "http://www.w3.org/XML/1998/namespace" XMLNS_NAMESPACE = "http://www.w3.org/2000/xmlns/" XHTML_NAMESPACE = "http://www.w3.org/1999/xhtml" EMPTY_NAMESPACE = None EMPTY_PREFIX = None from .domreg import getDOMImplementation, registerDOMImplementation domreg.py000064400000006573147204745200006413 0ustar00"""Registration facilities for DOM. This module should not be used directly. Instead, the functions getDOMImplementation and registerDOMImplementation should be imported from xml.dom.""" # This is a list of well-known implementations. Well-known names # should be published by posting to xml-sig@python.org, and are # subsequently recorded in this file. import sys well_known_implementations = { 'minidom':'xml.dom.minidom', '4DOM': 'xml.dom.DOMImplementation', } # DOM implementations not officially registered should register # themselves with their registered = {} def registerDOMImplementation(name, factory): """registerDOMImplementation(name, factory) Register the factory function with the name. The factory function should return an object which implements the DOMImplementation interface. The factory function can either return the same object, or a new one (e.g. if that implementation supports some customization).""" registered[name] = factory def _good_enough(dom, features): "_good_enough(dom, features) -> Return 1 if the dom offers the features" for f,v in features: if not dom.hasFeature(f,v): return 0 return 1 def getDOMImplementation(name=None, features=()): """getDOMImplementation(name = None, features = ()) -> DOM implementation. Return a suitable DOM implementation. The name is either well-known, the module name of a DOM implementation, or None. If it is not None, imports the corresponding module and returns DOMImplementation object if the import succeeds. If name is not given, consider the available implementations to find one with the required feature set. If no implementation can be found, raise an ImportError. The features list must be a sequence of (feature, version) pairs which are passed to hasFeature.""" import os creator = None mod = well_known_implementations.get(name) if mod: mod = __import__(mod, {}, {}, ['getDOMImplementation']) return mod.getDOMImplementation() elif name: return registered[name]() elif not sys.flags.ignore_environment and "PYTHON_DOM" in os.environ: return getDOMImplementation(name = os.environ["PYTHON_DOM"]) # User did not specify a name, try implementations in arbitrary # order, returning the one that has the required features if isinstance(features, str): features = _parse_feature_string(features) for creator in registered.values(): dom = creator() if _good_enough(dom, features): return dom for creator in well_known_implementations.keys(): try: dom = getDOMImplementation(name = creator) except Exception: # typically ImportError, or AttributeError continue if _good_enough(dom, features): return dom raise ImportError("no suitable DOM implementation found") def _parse_feature_string(s): features = [] parts = s.split() i = 0 length = len(parts) while i < length: feature = parts[i] if feature[0] in "0123456789": raise ValueError("bad feature name: %r" % (feature,)) i = i + 1 version = None if i < length: v = parts[i] if v[0] in "0123456789": i = i + 1 version = v features.append((feature, version)) return tuple(features) expatbuilder.py000064400000105654147204745200007626 0ustar00"""Facility to use the Expat parser to load a minidom instance from a string or file. This avoids all the overhead of SAX and pulldom to gain performance. """ # Warning! # # This module is tightly bound to the implementation details of the # minidom DOM and can't be used with other DOM implementations. This # is due, in part, to a lack of appropriate methods in the DOM (there is # no way to create Entity and Notation nodes via the DOM Level 2 # interface), and for performance. The latter is the cause of some fairly # cryptic code. # # Performance hacks: # # - .character_data_handler() has an extra case in which continuing # data is appended to an existing Text node; this can be a # speedup since pyexpat can break up character data into multiple # callbacks even though we set the buffer_text attribute on the # parser. This also gives us the advantage that we don't need a # separate normalization pass. # # - Determining that a node exists is done using an identity comparison # with None rather than a truth test; this avoids searching for and # calling any methods on the node object if it exists. (A rather # nice speedup is achieved this way as well!) from xml.dom import xmlbuilder, minidom, Node from xml.dom import EMPTY_NAMESPACE, EMPTY_PREFIX, XMLNS_NAMESPACE from xml.parsers import expat from xml.dom.minidom import _append_child, _set_attribute_node from xml.dom.NodeFilter import NodeFilter TEXT_NODE = Node.TEXT_NODE CDATA_SECTION_NODE = Node.CDATA_SECTION_NODE DOCUMENT_NODE = Node.DOCUMENT_NODE FILTER_ACCEPT = xmlbuilder.DOMBuilderFilter.FILTER_ACCEPT FILTER_REJECT = xmlbuilder.DOMBuilderFilter.FILTER_REJECT FILTER_SKIP = xmlbuilder.DOMBuilderFilter.FILTER_SKIP FILTER_INTERRUPT = xmlbuilder.DOMBuilderFilter.FILTER_INTERRUPT theDOMImplementation = minidom.getDOMImplementation() # Expat typename -> TypeInfo _typeinfo_map = { "CDATA": minidom.TypeInfo(None, "cdata"), "ENUM": minidom.TypeInfo(None, "enumeration"), "ENTITY": minidom.TypeInfo(None, "entity"), "ENTITIES": minidom.TypeInfo(None, "entities"), "ID": minidom.TypeInfo(None, "id"), "IDREF": minidom.TypeInfo(None, "idref"), "IDREFS": minidom.TypeInfo(None, "idrefs"), "NMTOKEN": minidom.TypeInfo(None, "nmtoken"), "NMTOKENS": minidom.TypeInfo(None, "nmtokens"), } class ElementInfo(object): __slots__ = '_attr_info', '_model', 'tagName' def __init__(self, tagName, model=None): self.tagName = tagName self._attr_info = [] self._model = model def __getstate__(self): return self._attr_info, self._model, self.tagName def __setstate__(self, state): self._attr_info, self._model, self.tagName = state def getAttributeType(self, aname): for info in self._attr_info: if info[1] == aname: t = info[-2] if t[0] == "(": return _typeinfo_map["ENUM"] else: return _typeinfo_map[info[-2]] return minidom._no_type def getAttributeTypeNS(self, namespaceURI, localName): return minidom._no_type def isElementContent(self): if self._model: type = self._model[0] return type not in (expat.model.XML_CTYPE_ANY, expat.model.XML_CTYPE_MIXED) else: return False def isEmpty(self): if self._model: return self._model[0] == expat.model.XML_CTYPE_EMPTY else: return False def isId(self, aname): for info in self._attr_info: if info[1] == aname: return info[-2] == "ID" return False def isIdNS(self, euri, ename, auri, aname): # not sure this is meaningful return self.isId((auri, aname)) def _intern(builder, s): return builder._intern_setdefault(s, s) def _parse_ns_name(builder, name): assert ' ' in name parts = name.split(' ') intern = builder._intern_setdefault if len(parts) == 3: uri, localname, prefix = parts prefix = intern(prefix, prefix) qname = "%s:%s" % (prefix, localname) qname = intern(qname, qname) localname = intern(localname, localname) elif len(parts) == 2: uri, localname = parts prefix = EMPTY_PREFIX qname = localname = intern(localname, localname) else: raise ValueError("Unsupported syntax: spaces in URIs not supported: %r" % name) return intern(uri, uri), localname, prefix, qname class ExpatBuilder: """Document builder that uses Expat to build a ParsedXML.DOM document instance.""" def __init__(self, options=None): if options is None: options = xmlbuilder.Options() self._options = options if self._options.filter is not None: self._filter = FilterVisibilityController(self._options.filter) else: self._filter = None # This *really* doesn't do anything in this case, so # override it with something fast & minimal. self._finish_start_element = id self._parser = None self.reset() def createParser(self): """Create a new parser object.""" return expat.ParserCreate() def getParser(self): """Return the parser object, creating a new one if needed.""" if not self._parser: self._parser = self.createParser() self._intern_setdefault = self._parser.intern.setdefault self._parser.buffer_text = True self._parser.ordered_attributes = True self._parser.specified_attributes = True self.install(self._parser) return self._parser def reset(self): """Free all data structures used during DOM construction.""" self.document = theDOMImplementation.createDocument( EMPTY_NAMESPACE, None, None) self.curNode = self.document self._elem_info = self.document._elem_info self._cdata = False def install(self, parser): """Install the callbacks needed to build the DOM into the parser.""" # This creates circular references! parser.StartDoctypeDeclHandler = self.start_doctype_decl_handler parser.StartElementHandler = self.first_element_handler parser.EndElementHandler = self.end_element_handler parser.ProcessingInstructionHandler = self.pi_handler if self._options.entities: parser.EntityDeclHandler = self.entity_decl_handler parser.NotationDeclHandler = self.notation_decl_handler if self._options.comments: parser.CommentHandler = self.comment_handler if self._options.cdata_sections: parser.StartCdataSectionHandler = self.start_cdata_section_handler parser.EndCdataSectionHandler = self.end_cdata_section_handler parser.CharacterDataHandler = self.character_data_handler_cdata else: parser.CharacterDataHandler = self.character_data_handler parser.ExternalEntityRefHandler = self.external_entity_ref_handler parser.XmlDeclHandler = self.xml_decl_handler parser.ElementDeclHandler = self.element_decl_handler parser.AttlistDeclHandler = self.attlist_decl_handler def parseFile(self, file): """Parse a document from a file object, returning the document node.""" parser = self.getParser() first_buffer = True try: while 1: buffer = file.read(16*1024) if not buffer: break parser.Parse(buffer, 0) if first_buffer and self.document.documentElement: self._setup_subset(buffer) first_buffer = False parser.Parse("", True) except ParseEscape: pass doc = self.document self.reset() self._parser = None return doc def parseString(self, string): """Parse a document from a string, returning the document node.""" parser = self.getParser() try: parser.Parse(string, True) self._setup_subset(string) except ParseEscape: pass doc = self.document self.reset() self._parser = None return doc def _setup_subset(self, buffer): """Load the internal subset if there might be one.""" if self.document.doctype: extractor = InternalSubsetExtractor() extractor.parseString(buffer) subset = extractor.getSubset() self.document.doctype.internalSubset = subset def start_doctype_decl_handler(self, doctypeName, systemId, publicId, has_internal_subset): doctype = self.document.implementation.createDocumentType( doctypeName, publicId, systemId) doctype.ownerDocument = self.document _append_child(self.document, doctype) self.document.doctype = doctype if self._filter and self._filter.acceptNode(doctype) == FILTER_REJECT: self.document.doctype = None del self.document.childNodes[-1] doctype = None self._parser.EntityDeclHandler = None self._parser.NotationDeclHandler = None if has_internal_subset: if doctype is not None: doctype.entities._seq = [] doctype.notations._seq = [] self._parser.CommentHandler = None self._parser.ProcessingInstructionHandler = None self._parser.EndDoctypeDeclHandler = self.end_doctype_decl_handler def end_doctype_decl_handler(self): if self._options.comments: self._parser.CommentHandler = self.comment_handler self._parser.ProcessingInstructionHandler = self.pi_handler if not (self._elem_info or self._filter): self._finish_end_element = id def pi_handler(self, target, data): node = self.document.createProcessingInstruction(target, data) _append_child(self.curNode, node) if self._filter and self._filter.acceptNode(node) == FILTER_REJECT: self.curNode.removeChild(node) def character_data_handler_cdata(self, data): childNodes = self.curNode.childNodes if self._cdata: if ( self._cdata_continue and childNodes[-1].nodeType == CDATA_SECTION_NODE): childNodes[-1].appendData(data) return node = self.document.createCDATASection(data) self._cdata_continue = True elif childNodes and childNodes[-1].nodeType == TEXT_NODE: node = childNodes[-1] value = node.data + data node.data = value return else: node = minidom.Text() node.data = data node.ownerDocument = self.document _append_child(self.curNode, node) def character_data_handler(self, data): childNodes = self.curNode.childNodes if childNodes and childNodes[-1].nodeType == TEXT_NODE: node = childNodes[-1] node.data = node.data + data return node = minidom.Text() node.data = node.data + data node.ownerDocument = self.document _append_child(self.curNode, node) def entity_decl_handler(self, entityName, is_parameter_entity, value, base, systemId, publicId, notationName): if is_parameter_entity: # we don't care about parameter entities for the DOM return if not self._options.entities: return node = self.document._create_entity(entityName, publicId, systemId, notationName) if value is not None: # internal entity # node *should* be readonly, but we'll cheat child = self.document.createTextNode(value) node.childNodes.append(child) self.document.doctype.entities._seq.append(node) if self._filter and self._filter.acceptNode(node) == FILTER_REJECT: del self.document.doctype.entities._seq[-1] def notation_decl_handler(self, notationName, base, systemId, publicId): node = self.document._create_notation(notationName, publicId, systemId) self.document.doctype.notations._seq.append(node) if self._filter and self._filter.acceptNode(node) == FILTER_ACCEPT: del self.document.doctype.notations._seq[-1] def comment_handler(self, data): node = self.document.createComment(data) _append_child(self.curNode, node) if self._filter and self._filter.acceptNode(node) == FILTER_REJECT: self.curNode.removeChild(node) def start_cdata_section_handler(self): self._cdata = True self._cdata_continue = False def end_cdata_section_handler(self): self._cdata = False self._cdata_continue = False def external_entity_ref_handler(self, context, base, systemId, publicId): return 1 def first_element_handler(self, name, attributes): if self._filter is None and not self._elem_info: self._finish_end_element = id self.getParser().StartElementHandler = self.start_element_handler self.start_element_handler(name, attributes) def start_element_handler(self, name, attributes): node = self.document.createElement(name) _append_child(self.curNode, node) self.curNode = node if attributes: for i in range(0, len(attributes), 2): a = minidom.Attr(attributes[i], EMPTY_NAMESPACE, None, EMPTY_PREFIX) value = attributes[i+1] a.value = value a.ownerDocument = self.document _set_attribute_node(node, a) if node is not self.document.documentElement: self._finish_start_element(node) def _finish_start_element(self, node): if self._filter: # To be general, we'd have to call isSameNode(), but this # is sufficient for minidom: if node is self.document.documentElement: return filt = self._filter.startContainer(node) if filt == FILTER_REJECT: # ignore this node & all descendents Rejecter(self) elif filt == FILTER_SKIP: # ignore this node, but make it's children become # children of the parent node Skipper(self) else: return self.curNode = node.parentNode node.parentNode.removeChild(node) node.unlink() # If this ever changes, Namespaces.end_element_handler() needs to # be changed to match. # def end_element_handler(self, name): curNode = self.curNode self.curNode = curNode.parentNode self._finish_end_element(curNode) def _finish_end_element(self, curNode): info = self._elem_info.get(curNode.tagName) if info: self._handle_white_text_nodes(curNode, info) if self._filter: if curNode is self.document.documentElement: return if self._filter.acceptNode(curNode) == FILTER_REJECT: self.curNode.removeChild(curNode) curNode.unlink() def _handle_white_text_nodes(self, node, info): if (self._options.whitespace_in_element_content or not info.isElementContent()): return # We have element type information and should remove ignorable # whitespace; identify for text nodes which contain only # whitespace. L = [] for child in node.childNodes: if child.nodeType == TEXT_NODE and not child.data.strip(): L.append(child) # Remove ignorable whitespace from the tree. for child in L: node.removeChild(child) def element_decl_handler(self, name, model): info = self._elem_info.get(name) if info is None: self._elem_info[name] = ElementInfo(name, model) else: assert info._model is None info._model = model def attlist_decl_handler(self, elem, name, type, default, required): info = self._elem_info.get(elem) if info is None: info = ElementInfo(elem) self._elem_info[elem] = info info._attr_info.append( [None, name, None, None, default, 0, type, required]) def xml_decl_handler(self, version, encoding, standalone): self.document.version = version self.document.encoding = encoding # This is still a little ugly, thanks to the pyexpat API. ;-( if standalone >= 0: if standalone: self.document.standalone = True else: self.document.standalone = False # Don't include FILTER_INTERRUPT, since that's checked separately # where allowed. _ALLOWED_FILTER_RETURNS = (FILTER_ACCEPT, FILTER_REJECT, FILTER_SKIP) class FilterVisibilityController(object): """Wrapper around a DOMBuilderFilter which implements the checks to make the whatToShow filter attribute work.""" __slots__ = 'filter', def __init__(self, filter): self.filter = filter def startContainer(self, node): mask = self._nodetype_mask[node.nodeType] if self.filter.whatToShow & mask: val = self.filter.startContainer(node) if val == FILTER_INTERRUPT: raise ParseEscape if val not in _ALLOWED_FILTER_RETURNS: raise ValueError( "startContainer() returned illegal value: " + repr(val)) return val else: return FILTER_ACCEPT def acceptNode(self, node): mask = self._nodetype_mask[node.nodeType] if self.filter.whatToShow & mask: val = self.filter.acceptNode(node) if val == FILTER_INTERRUPT: raise ParseEscape if val == FILTER_SKIP: # move all child nodes to the parent, and remove this node parent = node.parentNode for child in node.childNodes[:]: parent.appendChild(child) # node is handled by the caller return FILTER_REJECT if val not in _ALLOWED_FILTER_RETURNS: raise ValueError( "acceptNode() returned illegal value: " + repr(val)) return val else: return FILTER_ACCEPT _nodetype_mask = { Node.ELEMENT_NODE: NodeFilter.SHOW_ELEMENT, Node.ATTRIBUTE_NODE: NodeFilter.SHOW_ATTRIBUTE, Node.TEXT_NODE: NodeFilter.SHOW_TEXT, Node.CDATA_SECTION_NODE: NodeFilter.SHOW_CDATA_SECTION, Node.ENTITY_REFERENCE_NODE: NodeFilter.SHOW_ENTITY_REFERENCE, Node.ENTITY_NODE: NodeFilter.SHOW_ENTITY, Node.PROCESSING_INSTRUCTION_NODE: NodeFilter.SHOW_PROCESSING_INSTRUCTION, Node.COMMENT_NODE: NodeFilter.SHOW_COMMENT, Node.DOCUMENT_NODE: NodeFilter.SHOW_DOCUMENT, Node.DOCUMENT_TYPE_NODE: NodeFilter.SHOW_DOCUMENT_TYPE, Node.DOCUMENT_FRAGMENT_NODE: NodeFilter.SHOW_DOCUMENT_FRAGMENT, Node.NOTATION_NODE: NodeFilter.SHOW_NOTATION, } class FilterCrutch(object): __slots__ = '_builder', '_level', '_old_start', '_old_end' def __init__(self, builder): self._level = 0 self._builder = builder parser = builder._parser self._old_start = parser.StartElementHandler self._old_end = parser.EndElementHandler parser.StartElementHandler = self.start_element_handler parser.EndElementHandler = self.end_element_handler class Rejecter(FilterCrutch): __slots__ = () def __init__(self, builder): FilterCrutch.__init__(self, builder) parser = builder._parser for name in ("ProcessingInstructionHandler", "CommentHandler", "CharacterDataHandler", "StartCdataSectionHandler", "EndCdataSectionHandler", "ExternalEntityRefHandler", ): setattr(parser, name, None) def start_element_handler(self, *args): self._level = self._level + 1 def end_element_handler(self, *args): if self._level == 0: # restore the old handlers parser = self._builder._parser self._builder.install(parser) parser.StartElementHandler = self._old_start parser.EndElementHandler = self._old_end else: self._level = self._level - 1 class Skipper(FilterCrutch): __slots__ = () def start_element_handler(self, *args): node = self._builder.curNode self._old_start(*args) if self._builder.curNode is not node: self._level = self._level + 1 def end_element_handler(self, *args): if self._level == 0: # We're popping back out of the node we're skipping, so we # shouldn't need to do anything but reset the handlers. self._builder._parser.StartElementHandler = self._old_start self._builder._parser.EndElementHandler = self._old_end self._builder = None else: self._level = self._level - 1 self._old_end(*args) # framework document used by the fragment builder. # Takes a string for the doctype, subset string, and namespace attrs string. _FRAGMENT_BUILDER_INTERNAL_SYSTEM_ID = \ "http://xml.python.org/entities/fragment-builder/internal" _FRAGMENT_BUILDER_TEMPLATE = ( '''\ %%s ]> &fragment-builder-internal;''' % _FRAGMENT_BUILDER_INTERNAL_SYSTEM_ID) class FragmentBuilder(ExpatBuilder): """Builder which constructs document fragments given XML source text and a context node. The context node is expected to provide information about the namespace declarations which are in scope at the start of the fragment. """ def __init__(self, context, options=None): if context.nodeType == DOCUMENT_NODE: self.originalDocument = context self.context = context else: self.originalDocument = context.ownerDocument self.context = context ExpatBuilder.__init__(self, options) def reset(self): ExpatBuilder.reset(self) self.fragment = None def parseFile(self, file): """Parse a document fragment from a file object, returning the fragment node.""" return self.parseString(file.read()) def parseString(self, string): """Parse a document fragment from a string, returning the fragment node.""" self._source = string parser = self.getParser() doctype = self.originalDocument.doctype ident = "" if doctype: subset = doctype.internalSubset or self._getDeclarations() if doctype.publicId: ident = ('PUBLIC "%s" "%s"' % (doctype.publicId, doctype.systemId)) elif doctype.systemId: ident = 'SYSTEM "%s"' % doctype.systemId else: subset = "" nsattrs = self._getNSattrs() # get ns decls from node's ancestors document = _FRAGMENT_BUILDER_TEMPLATE % (ident, subset, nsattrs) try: parser.Parse(document, 1) except: self.reset() raise fragment = self.fragment self.reset() ## self._parser = None return fragment def _getDeclarations(self): """Re-create the internal subset from the DocumentType node. This is only needed if we don't already have the internalSubset as a string. """ doctype = self.context.ownerDocument.doctype s = "" if doctype: for i in range(doctype.notations.length): notation = doctype.notations.item(i) if s: s = s + "\n " s = "%s' \ % (s, notation.publicId, notation.systemId) else: s = '%s SYSTEM "%s">' % (s, notation.systemId) for i in range(doctype.entities.length): entity = doctype.entities.item(i) if s: s = s + "\n " s = "%s" return s def _getNSattrs(self): return "" def external_entity_ref_handler(self, context, base, systemId, publicId): if systemId == _FRAGMENT_BUILDER_INTERNAL_SYSTEM_ID: # this entref is the one that we made to put the subtree # in; all of our given input is parsed in here. old_document = self.document old_cur_node = self.curNode parser = self._parser.ExternalEntityParserCreate(context) # put the real document back, parse into the fragment to return self.document = self.originalDocument self.fragment = self.document.createDocumentFragment() self.curNode = self.fragment try: parser.Parse(self._source, 1) finally: self.curNode = old_cur_node self.document = old_document self._source = None return -1 else: return ExpatBuilder.external_entity_ref_handler( self, context, base, systemId, publicId) class Namespaces: """Mix-in class for builders; adds support for namespaces.""" def _initNamespaces(self): # list of (prefix, uri) ns declarations. Namespace attrs are # constructed from this and added to the element's attrs. self._ns_ordered_prefixes = [] def createParser(self): """Create a new namespace-handling parser.""" parser = expat.ParserCreate(namespace_separator=" ") parser.namespace_prefixes = True return parser def install(self, parser): """Insert the namespace-handlers onto the parser.""" ExpatBuilder.install(self, parser) if self._options.namespace_declarations: parser.StartNamespaceDeclHandler = ( self.start_namespace_decl_handler) def start_namespace_decl_handler(self, prefix, uri): """Push this namespace declaration on our storage.""" self._ns_ordered_prefixes.append((prefix, uri)) def start_element_handler(self, name, attributes): if ' ' in name: uri, localname, prefix, qname = _parse_ns_name(self, name) else: uri = EMPTY_NAMESPACE qname = name localname = None prefix = EMPTY_PREFIX node = minidom.Element(qname, uri, prefix, localname) node.ownerDocument = self.document _append_child(self.curNode, node) self.curNode = node if self._ns_ordered_prefixes: for prefix, uri in self._ns_ordered_prefixes: if prefix: a = minidom.Attr(_intern(self, 'xmlns:' + prefix), XMLNS_NAMESPACE, prefix, "xmlns") else: a = minidom.Attr("xmlns", XMLNS_NAMESPACE, "xmlns", EMPTY_PREFIX) a.value = uri a.ownerDocument = self.document _set_attribute_node(node, a) del self._ns_ordered_prefixes[:] if attributes: node._ensure_attributes() _attrs = node._attrs _attrsNS = node._attrsNS for i in range(0, len(attributes), 2): aname = attributes[i] value = attributes[i+1] if ' ' in aname: uri, localname, prefix, qname = _parse_ns_name(self, aname) a = minidom.Attr(qname, uri, localname, prefix) _attrs[qname] = a _attrsNS[(uri, localname)] = a else: a = minidom.Attr(aname, EMPTY_NAMESPACE, aname, EMPTY_PREFIX) _attrs[aname] = a _attrsNS[(EMPTY_NAMESPACE, aname)] = a a.ownerDocument = self.document a.value = value a.ownerElement = node if __debug__: # This only adds some asserts to the original # end_element_handler(), so we only define this when -O is not # used. If changing one, be sure to check the other to see if # it needs to be changed as well. # def end_element_handler(self, name): curNode = self.curNode if ' ' in name: uri, localname, prefix, qname = _parse_ns_name(self, name) assert (curNode.namespaceURI == uri and curNode.localName == localname and curNode.prefix == prefix), \ "element stack messed up! (namespace)" else: assert curNode.nodeName == name, \ "element stack messed up - bad nodeName" assert curNode.namespaceURI == EMPTY_NAMESPACE, \ "element stack messed up - bad namespaceURI" self.curNode = curNode.parentNode self._finish_end_element(curNode) class ExpatBuilderNS(Namespaces, ExpatBuilder): """Document builder that supports namespaces.""" def reset(self): ExpatBuilder.reset(self) self._initNamespaces() class FragmentBuilderNS(Namespaces, FragmentBuilder): """Fragment builder that supports namespaces.""" def reset(self): FragmentBuilder.reset(self) self._initNamespaces() def _getNSattrs(self): """Return string of namespace attributes from this element and ancestors.""" # XXX This needs to be re-written to walk the ancestors of the # context to build up the namespace information from # declarations, elements, and attributes found in context. # Otherwise we have to store a bunch more data on the DOM # (though that *might* be more reliable -- not clear). attrs = "" context = self.context L = [] while context: if hasattr(context, '_ns_prefix_uri'): for prefix, uri in context._ns_prefix_uri.items(): # add every new NS decl from context to L and attrs string if prefix in L: continue L.append(prefix) if prefix: declname = "xmlns:" + prefix else: declname = "xmlns" if attrs: attrs = "%s\n %s='%s'" % (attrs, declname, uri) else: attrs = " %s='%s'" % (declname, uri) context = context.parentNode return attrs class ParseEscape(Exception): """Exception raised to short-circuit parsing in InternalSubsetExtractor.""" pass class InternalSubsetExtractor(ExpatBuilder): """XML processor which can rip out the internal document type subset.""" subset = None def getSubset(self): """Return the internal subset as a string.""" return self.subset def parseFile(self, file): try: ExpatBuilder.parseFile(self, file) except ParseEscape: pass def parseString(self, string): try: ExpatBuilder.parseString(self, string) except ParseEscape: pass def install(self, parser): parser.StartDoctypeDeclHandler = self.start_doctype_decl_handler parser.StartElementHandler = self.start_element_handler def start_doctype_decl_handler(self, name, publicId, systemId, has_internal_subset): if has_internal_subset: parser = self.getParser() self.subset = [] parser.DefaultHandler = self.subset.append parser.EndDoctypeDeclHandler = self.end_doctype_decl_handler else: raise ParseEscape() def end_doctype_decl_handler(self): s = ''.join(self.subset).replace('\r\n', '\n').replace('\r', '\n') self.subset = s raise ParseEscape() def start_element_handler(self, name, attrs): raise ParseEscape() def parse(file, namespaces=True): """Parse a document, returning the resulting Document node. 'file' may be either a file name or an open file object. """ if namespaces: builder = ExpatBuilderNS() else: builder = ExpatBuilder() if isinstance(file, str): with open(file, 'rb') as fp: result = builder.parseFile(fp) else: result = builder.parseFile(file) return result def parseString(string, namespaces=True): """Parse a document from a string, returning the resulting Document node. """ if namespaces: builder = ExpatBuilderNS() else: builder = ExpatBuilder() return builder.parseString(string) def parseFragment(file, context, namespaces=True): """Parse a fragment of a document, given the context from which it was originally extracted. context should be the parent of the node(s) which are in the fragment. 'file' may be either a file name or an open file object. """ if namespaces: builder = FragmentBuilderNS(context) else: builder = FragmentBuilder(context) if isinstance(file, str): with open(file, 'rb') as fp: result = builder.parseFile(fp) else: result = builder.parseFile(file) return result def parseFragmentString(string, context, namespaces=True): """Parse a fragment of a document from a string, given the context from which it was originally extracted. context should be the parent of the node(s) which are in the fragment. """ if namespaces: builder = FragmentBuilderNS(context) else: builder = FragmentBuilder(context) return builder.parseString(string) def makeBuilder(options): """Create a builder based on an Options object.""" if options.namespaces: return ExpatBuilderNS(options) else: return ExpatBuilder(options) minicompat.py000064400000006447147204745200007276 0ustar00"""Python version compatibility support for minidom. This module contains internal implementation details and should not be imported; use xml.dom.minidom instead. """ # This module should only be imported using "import *". # # The following names are defined: # # NodeList -- lightest possible NodeList implementation # # EmptyNodeList -- lightest possible NodeList that is guaranteed to # remain empty (immutable) # # StringTypes -- tuple of defined string types # # defproperty -- function used in conjunction with GetattrMagic; # using these together is needed to make them work # as efficiently as possible in both Python 2.2+ # and older versions. For example: # # class MyClass(GetattrMagic): # def _get_myattr(self): # return something # # defproperty(MyClass, "myattr", # "return some value") # # For Python 2.2 and newer, this will construct a # property object on the class, which avoids # needing to override __getattr__(). It will only # work for read-only attributes. # # For older versions of Python, inheriting from # GetattrMagic will use the traditional # __getattr__() hackery to achieve the same effect, # but less efficiently. # # defproperty() should be used for each version of # the relevant _get_() function. __all__ = ["NodeList", "EmptyNodeList", "StringTypes", "defproperty"] import xml.dom StringTypes = (str,) class NodeList(list): __slots__ = () def item(self, index): if 0 <= index < len(self): return self[index] def _get_length(self): return len(self) def _set_length(self, value): raise xml.dom.NoModificationAllowedErr( "attempt to modify read-only attribute 'length'") length = property(_get_length, _set_length, doc="The number of nodes in the NodeList.") # For backward compatibility def __setstate__(self, state): if state is None: state = [] self[:] = state class EmptyNodeList(tuple): __slots__ = () def __add__(self, other): NL = NodeList() NL.extend(other) return NL def __radd__(self, other): NL = NodeList() NL.extend(other) return NL def item(self, index): return None def _get_length(self): return 0 def _set_length(self, value): raise xml.dom.NoModificationAllowedErr( "attempt to modify read-only attribute 'length'") length = property(_get_length, _set_length, doc="The number of nodes in the NodeList.") def defproperty(klass, name, doc): get = getattr(klass, ("_get_" + name)) def set(self, value, name=name): raise xml.dom.NoModificationAllowedErr( "attempt to modify read-only attribute " + repr(name)) assert not hasattr(klass, "_set_" + name), \ "expected not to find _set_" + name prop = property(get, set, doc=doc) setattr(klass, name, prop) minidom.py000064400000202403147204745200006560 0ustar00"""Simple implementation of the Level 1 DOM. Namespaces and other minor Level 2 features are also supported. parse("foo.xml") parseString("") Todo: ===== * convenience methods for getting elements and text. * more testing * bring some of the writer and linearizer code into conformance with this interface * SAX 2 namespaces """ import io import xml.dom from xml.dom import EMPTY_NAMESPACE, EMPTY_PREFIX, XMLNS_NAMESPACE, domreg from xml.dom.minicompat import * from xml.dom.xmlbuilder import DOMImplementationLS, DocumentLS # This is used by the ID-cache invalidation checks; the list isn't # actually complete, since the nodes being checked will never be the # DOCUMENT_NODE or DOCUMENT_FRAGMENT_NODE. (The node being checked is # the node being added or removed, not the node being modified.) # _nodeTypes_with_children = (xml.dom.Node.ELEMENT_NODE, xml.dom.Node.ENTITY_REFERENCE_NODE) class Node(xml.dom.Node): namespaceURI = None # this is non-null only for elements and attributes parentNode = None ownerDocument = None nextSibling = None previousSibling = None prefix = EMPTY_PREFIX # non-null only for NS elements and attributes def __bool__(self): return True def toxml(self, encoding=None): return self.toprettyxml("", "", encoding) def toprettyxml(self, indent="\t", newl="\n", encoding=None): if encoding is None: writer = io.StringIO() else: writer = io.TextIOWrapper(io.BytesIO(), encoding=encoding, errors="xmlcharrefreplace", newline='\n') if self.nodeType == Node.DOCUMENT_NODE: # Can pass encoding only to document, to put it into XML header self.writexml(writer, "", indent, newl, encoding) else: self.writexml(writer, "", indent, newl) if encoding is None: return writer.getvalue() else: return writer.detach().getvalue() def hasChildNodes(self): return bool(self.childNodes) def _get_childNodes(self): return self.childNodes def _get_firstChild(self): if self.childNodes: return self.childNodes[0] def _get_lastChild(self): if self.childNodes: return self.childNodes[-1] def insertBefore(self, newChild, refChild): if newChild.nodeType == self.DOCUMENT_FRAGMENT_NODE: for c in tuple(newChild.childNodes): self.insertBefore(c, refChild) ### The DOM does not clearly specify what to return in this case return newChild if newChild.nodeType not in self._child_node_types: raise xml.dom.HierarchyRequestErr( "%s cannot be child of %s" % (repr(newChild), repr(self))) if newChild.parentNode is not None: newChild.parentNode.removeChild(newChild) if refChild is None: self.appendChild(newChild) else: try: index = self.childNodes.index(refChild) except ValueError: raise xml.dom.NotFoundErr() if newChild.nodeType in _nodeTypes_with_children: _clear_id_cache(self) self.childNodes.insert(index, newChild) newChild.nextSibling = refChild refChild.previousSibling = newChild if index: node = self.childNodes[index-1] node.nextSibling = newChild newChild.previousSibling = node else: newChild.previousSibling = None newChild.parentNode = self return newChild def appendChild(self, node): if node.nodeType == self.DOCUMENT_FRAGMENT_NODE: for c in tuple(node.childNodes): self.appendChild(c) ### The DOM does not clearly specify what to return in this case return node if node.nodeType not in self._child_node_types: raise xml.dom.HierarchyRequestErr( "%s cannot be child of %s" % (repr(node), repr(self))) elif node.nodeType in _nodeTypes_with_children: _clear_id_cache(self) if node.parentNode is not None: node.parentNode.removeChild(node) _append_child(self, node) node.nextSibling = None return node def replaceChild(self, newChild, oldChild): if newChild.nodeType == self.DOCUMENT_FRAGMENT_NODE: refChild = oldChild.nextSibling self.removeChild(oldChild) return self.insertBefore(newChild, refChild) if newChild.nodeType not in self._child_node_types: raise xml.dom.HierarchyRequestErr( "%s cannot be child of %s" % (repr(newChild), repr(self))) if newChild is oldChild: return if newChild.parentNode is not None: newChild.parentNode.removeChild(newChild) try: index = self.childNodes.index(oldChild) except ValueError: raise xml.dom.NotFoundErr() self.childNodes[index] = newChild newChild.parentNode = self oldChild.parentNode = None if (newChild.nodeType in _nodeTypes_with_children or oldChild.nodeType in _nodeTypes_with_children): _clear_id_cache(self) newChild.nextSibling = oldChild.nextSibling newChild.previousSibling = oldChild.previousSibling oldChild.nextSibling = None oldChild.previousSibling = None if newChild.previousSibling: newChild.previousSibling.nextSibling = newChild if newChild.nextSibling: newChild.nextSibling.previousSibling = newChild return oldChild def removeChild(self, oldChild): try: self.childNodes.remove(oldChild) except ValueError: raise xml.dom.NotFoundErr() if oldChild.nextSibling is not None: oldChild.nextSibling.previousSibling = oldChild.previousSibling if oldChild.previousSibling is not None: oldChild.previousSibling.nextSibling = oldChild.nextSibling oldChild.nextSibling = oldChild.previousSibling = None if oldChild.nodeType in _nodeTypes_with_children: _clear_id_cache(self) oldChild.parentNode = None return oldChild def normalize(self): L = [] for child in self.childNodes: if child.nodeType == Node.TEXT_NODE: if not child.data: # empty text node; discard if L: L[-1].nextSibling = child.nextSibling if child.nextSibling: child.nextSibling.previousSibling = child.previousSibling child.unlink() elif L and L[-1].nodeType == child.nodeType: # collapse text node node = L[-1] node.data = node.data + child.data node.nextSibling = child.nextSibling if child.nextSibling: child.nextSibling.previousSibling = node child.unlink() else: L.append(child) else: L.append(child) if child.nodeType == Node.ELEMENT_NODE: child.normalize() self.childNodes[:] = L def cloneNode(self, deep): return _clone_node(self, deep, self.ownerDocument or self) def isSupported(self, feature, version): return self.ownerDocument.implementation.hasFeature(feature, version) def _get_localName(self): # Overridden in Element and Attr where localName can be Non-Null return None # Node interfaces from Level 3 (WD 9 April 2002) def isSameNode(self, other): return self is other def getInterface(self, feature): if self.isSupported(feature, None): return self else: return None # The "user data" functions use a dictionary that is only present # if some user data has been set, so be careful not to assume it # exists. def getUserData(self, key): try: return self._user_data[key][0] except (AttributeError, KeyError): return None def setUserData(self, key, data, handler): old = None try: d = self._user_data except AttributeError: d = {} self._user_data = d if key in d: old = d[key][0] if data is None: # ignore handlers passed for None handler = None if old is not None: del d[key] else: d[key] = (data, handler) return old def _call_user_data_handler(self, operation, src, dst): if hasattr(self, "_user_data"): for key, (data, handler) in list(self._user_data.items()): if handler is not None: handler.handle(operation, key, data, src, dst) # minidom-specific API: def unlink(self): self.parentNode = self.ownerDocument = None if self.childNodes: for child in self.childNodes: child.unlink() self.childNodes = NodeList() self.previousSibling = None self.nextSibling = None # A Node is its own context manager, to ensure that an unlink() call occurs. # This is similar to how a file object works. def __enter__(self): return self def __exit__(self, et, ev, tb): self.unlink() defproperty(Node, "firstChild", doc="First child node, or None.") defproperty(Node, "lastChild", doc="Last child node, or None.") defproperty(Node, "localName", doc="Namespace-local name of this node.") def _append_child(self, node): # fast path with less checks; usable by DOM builders if careful childNodes = self.childNodes if childNodes: last = childNodes[-1] node.previousSibling = last last.nextSibling = node childNodes.append(node) node.parentNode = self def _in_document(node): # return True iff node is part of a document tree while node is not None: if node.nodeType == Node.DOCUMENT_NODE: return True node = node.parentNode return False def _write_data(writer, data): "Writes datachars to writer." if data: data = data.replace("&", "&").replace("<", "<"). \ replace("\"", """).replace(">", ">") writer.write(data) def _get_elements_by_tagName_helper(parent, name, rc): for node in parent.childNodes: if node.nodeType == Node.ELEMENT_NODE and \ (name == "*" or node.tagName == name): rc.append(node) _get_elements_by_tagName_helper(node, name, rc) return rc def _get_elements_by_tagName_ns_helper(parent, nsURI, localName, rc): for node in parent.childNodes: if node.nodeType == Node.ELEMENT_NODE: if ((localName == "*" or node.localName == localName) and (nsURI == "*" or node.namespaceURI == nsURI)): rc.append(node) _get_elements_by_tagName_ns_helper(node, nsURI, localName, rc) return rc class DocumentFragment(Node): nodeType = Node.DOCUMENT_FRAGMENT_NODE nodeName = "#document-fragment" nodeValue = None attributes = None parentNode = None _child_node_types = (Node.ELEMENT_NODE, Node.TEXT_NODE, Node.CDATA_SECTION_NODE, Node.ENTITY_REFERENCE_NODE, Node.PROCESSING_INSTRUCTION_NODE, Node.COMMENT_NODE, Node.NOTATION_NODE) def __init__(self): self.childNodes = NodeList() class Attr(Node): __slots__=('_name', '_value', 'namespaceURI', '_prefix', 'childNodes', '_localName', 'ownerDocument', 'ownerElement') nodeType = Node.ATTRIBUTE_NODE attributes = None specified = False _is_id = False _child_node_types = (Node.TEXT_NODE, Node.ENTITY_REFERENCE_NODE) def __init__(self, qName, namespaceURI=EMPTY_NAMESPACE, localName=None, prefix=None): self.ownerElement = None self._name = qName self.namespaceURI = namespaceURI self._prefix = prefix self.childNodes = NodeList() # Add the single child node that represents the value of the attr self.childNodes.append(Text()) # nodeValue and value are set elsewhere def _get_localName(self): try: return self._localName except AttributeError: return self.nodeName.split(":", 1)[-1] def _get_specified(self): return self.specified def _get_name(self): return self._name def _set_name(self, value): self._name = value if self.ownerElement is not None: _clear_id_cache(self.ownerElement) nodeName = name = property(_get_name, _set_name) def _get_value(self): return self._value def _set_value(self, value): self._value = value self.childNodes[0].data = value if self.ownerElement is not None: _clear_id_cache(self.ownerElement) self.childNodes[0].data = value nodeValue = value = property(_get_value, _set_value) def _get_prefix(self): return self._prefix def _set_prefix(self, prefix): nsuri = self.namespaceURI if prefix == "xmlns": if nsuri and nsuri != XMLNS_NAMESPACE: raise xml.dom.NamespaceErr( "illegal use of 'xmlns' prefix for the wrong namespace") self._prefix = prefix if prefix is None: newName = self.localName else: newName = "%s:%s" % (prefix, self.localName) if self.ownerElement: _clear_id_cache(self.ownerElement) self.name = newName prefix = property(_get_prefix, _set_prefix) def unlink(self): # This implementation does not call the base implementation # since most of that is not needed, and the expense of the # method call is not warranted. We duplicate the removal of # children, but that's all we needed from the base class. elem = self.ownerElement if elem is not None: del elem._attrs[self.nodeName] del elem._attrsNS[(self.namespaceURI, self.localName)] if self._is_id: self._is_id = False elem._magic_id_nodes -= 1 self.ownerDocument._magic_id_count -= 1 for child in self.childNodes: child.unlink() del self.childNodes[:] def _get_isId(self): if self._is_id: return True doc = self.ownerDocument elem = self.ownerElement if doc is None or elem is None: return False info = doc._get_elem_info(elem) if info is None: return False if self.namespaceURI: return info.isIdNS(self.namespaceURI, self.localName) else: return info.isId(self.nodeName) def _get_schemaType(self): doc = self.ownerDocument elem = self.ownerElement if doc is None or elem is None: return _no_type info = doc._get_elem_info(elem) if info is None: return _no_type if self.namespaceURI: return info.getAttributeTypeNS(self.namespaceURI, self.localName) else: return info.getAttributeType(self.nodeName) defproperty(Attr, "isId", doc="True if this attribute is an ID.") defproperty(Attr, "localName", doc="Namespace-local name of this attribute.") defproperty(Attr, "schemaType", doc="Schema type for this attribute.") class NamedNodeMap(object): """The attribute list is a transient interface to the underlying dictionaries. Mutations here will change the underlying element's dictionary. Ordering is imposed artificially and does not reflect the order of attributes as found in an input document. """ __slots__ = ('_attrs', '_attrsNS', '_ownerElement') def __init__(self, attrs, attrsNS, ownerElement): self._attrs = attrs self._attrsNS = attrsNS self._ownerElement = ownerElement def _get_length(self): return len(self._attrs) def item(self, index): try: return self[list(self._attrs.keys())[index]] except IndexError: return None def items(self): L = [] for node in self._attrs.values(): L.append((node.nodeName, node.value)) return L def itemsNS(self): L = [] for node in self._attrs.values(): L.append(((node.namespaceURI, node.localName), node.value)) return L def __contains__(self, key): if isinstance(key, str): return key in self._attrs else: return key in self._attrsNS def keys(self): return self._attrs.keys() def keysNS(self): return self._attrsNS.keys() def values(self): return self._attrs.values() def get(self, name, value=None): return self._attrs.get(name, value) __len__ = _get_length def _cmp(self, other): if self._attrs is getattr(other, "_attrs", None): return 0 else: return (id(self) > id(other)) - (id(self) < id(other)) def __eq__(self, other): return self._cmp(other) == 0 def __ge__(self, other): return self._cmp(other) >= 0 def __gt__(self, other): return self._cmp(other) > 0 def __le__(self, other): return self._cmp(other) <= 0 def __lt__(self, other): return self._cmp(other) < 0 def __getitem__(self, attname_or_tuple): if isinstance(attname_or_tuple, tuple): return self._attrsNS[attname_or_tuple] else: return self._attrs[attname_or_tuple] # same as set def __setitem__(self, attname, value): if isinstance(value, str): try: node = self._attrs[attname] except KeyError: node = Attr(attname) node.ownerDocument = self._ownerElement.ownerDocument self.setNamedItem(node) node.value = value else: if not isinstance(value, Attr): raise TypeError("value must be a string or Attr object") node = value self.setNamedItem(node) def getNamedItem(self, name): try: return self._attrs[name] except KeyError: return None def getNamedItemNS(self, namespaceURI, localName): try: return self._attrsNS[(namespaceURI, localName)] except KeyError: return None def removeNamedItem(self, name): n = self.getNamedItem(name) if n is not None: _clear_id_cache(self._ownerElement) del self._attrs[n.nodeName] del self._attrsNS[(n.namespaceURI, n.localName)] if hasattr(n, 'ownerElement'): n.ownerElement = None return n else: raise xml.dom.NotFoundErr() def removeNamedItemNS(self, namespaceURI, localName): n = self.getNamedItemNS(namespaceURI, localName) if n is not None: _clear_id_cache(self._ownerElement) del self._attrsNS[(n.namespaceURI, n.localName)] del self._attrs[n.nodeName] if hasattr(n, 'ownerElement'): n.ownerElement = None return n else: raise xml.dom.NotFoundErr() def setNamedItem(self, node): if not isinstance(node, Attr): raise xml.dom.HierarchyRequestErr( "%s cannot be child of %s" % (repr(node), repr(self))) old = self._attrs.get(node.name) if old: old.unlink() self._attrs[node.name] = node self._attrsNS[(node.namespaceURI, node.localName)] = node node.ownerElement = self._ownerElement _clear_id_cache(node.ownerElement) return old def setNamedItemNS(self, node): return self.setNamedItem(node) def __delitem__(self, attname_or_tuple): node = self[attname_or_tuple] _clear_id_cache(node.ownerElement) node.unlink() def __getstate__(self): return self._attrs, self._attrsNS, self._ownerElement def __setstate__(self, state): self._attrs, self._attrsNS, self._ownerElement = state defproperty(NamedNodeMap, "length", doc="Number of nodes in the NamedNodeMap.") AttributeList = NamedNodeMap class TypeInfo(object): __slots__ = 'namespace', 'name' def __init__(self, namespace, name): self.namespace = namespace self.name = name def __repr__(self): if self.namespace: return "<%s %r (from %r)>" % (self.__class__.__name__, self.name, self.namespace) else: return "<%s %r>" % (self.__class__.__name__, self.name) def _get_name(self): return self.name def _get_namespace(self): return self.namespace _no_type = TypeInfo(None, None) class Element(Node): __slots__=('ownerDocument', 'parentNode', 'tagName', 'nodeName', 'prefix', 'namespaceURI', '_localName', 'childNodes', '_attrs', '_attrsNS', 'nextSibling', 'previousSibling') nodeType = Node.ELEMENT_NODE nodeValue = None schemaType = _no_type _magic_id_nodes = 0 _child_node_types = (Node.ELEMENT_NODE, Node.PROCESSING_INSTRUCTION_NODE, Node.COMMENT_NODE, Node.TEXT_NODE, Node.CDATA_SECTION_NODE, Node.ENTITY_REFERENCE_NODE) def __init__(self, tagName, namespaceURI=EMPTY_NAMESPACE, prefix=None, localName=None): self.parentNode = None self.tagName = self.nodeName = tagName self.prefix = prefix self.namespaceURI = namespaceURI self.childNodes = NodeList() self.nextSibling = self.previousSibling = None # Attribute dictionaries are lazily created # attributes are double-indexed: # tagName -> Attribute # URI,localName -> Attribute # in the future: consider lazy generation # of attribute objects this is too tricky # for now because of headaches with # namespaces. self._attrs = None self._attrsNS = None def _ensure_attributes(self): if self._attrs is None: self._attrs = {} self._attrsNS = {} def _get_localName(self): try: return self._localName except AttributeError: return self.tagName.split(":", 1)[-1] def _get_tagName(self): return self.tagName def unlink(self): if self._attrs is not None: for attr in list(self._attrs.values()): attr.unlink() self._attrs = None self._attrsNS = None Node.unlink(self) def getAttribute(self, attname): if self._attrs is None: return "" try: return self._attrs[attname].value except KeyError: return "" def getAttributeNS(self, namespaceURI, localName): if self._attrsNS is None: return "" try: return self._attrsNS[(namespaceURI, localName)].value except KeyError: return "" def setAttribute(self, attname, value): attr = self.getAttributeNode(attname) if attr is None: attr = Attr(attname) attr.value = value # also sets nodeValue attr.ownerDocument = self.ownerDocument self.setAttributeNode(attr) elif value != attr.value: attr.value = value if attr.isId: _clear_id_cache(self) def setAttributeNS(self, namespaceURI, qualifiedName, value): prefix, localname = _nssplit(qualifiedName) attr = self.getAttributeNodeNS(namespaceURI, localname) if attr is None: attr = Attr(qualifiedName, namespaceURI, localname, prefix) attr.value = value attr.ownerDocument = self.ownerDocument self.setAttributeNode(attr) else: if value != attr.value: attr.value = value if attr.isId: _clear_id_cache(self) if attr.prefix != prefix: attr.prefix = prefix attr.nodeName = qualifiedName def getAttributeNode(self, attrname): if self._attrs is None: return None return self._attrs.get(attrname) def getAttributeNodeNS(self, namespaceURI, localName): if self._attrsNS is None: return None return self._attrsNS.get((namespaceURI, localName)) def setAttributeNode(self, attr): if attr.ownerElement not in (None, self): raise xml.dom.InuseAttributeErr("attribute node already owned") self._ensure_attributes() old1 = self._attrs.get(attr.name, None) if old1 is not None: self.removeAttributeNode(old1) old2 = self._attrsNS.get((attr.namespaceURI, attr.localName), None) if old2 is not None and old2 is not old1: self.removeAttributeNode(old2) _set_attribute_node(self, attr) if old1 is not attr: # It might have already been part of this node, in which case # it doesn't represent a change, and should not be returned. return old1 if old2 is not attr: return old2 setAttributeNodeNS = setAttributeNode def removeAttribute(self, name): if self._attrsNS is None: raise xml.dom.NotFoundErr() try: attr = self._attrs[name] except KeyError: raise xml.dom.NotFoundErr() self.removeAttributeNode(attr) def removeAttributeNS(self, namespaceURI, localName): if self._attrsNS is None: raise xml.dom.NotFoundErr() try: attr = self._attrsNS[(namespaceURI, localName)] except KeyError: raise xml.dom.NotFoundErr() self.removeAttributeNode(attr) def removeAttributeNode(self, node): if node is None: raise xml.dom.NotFoundErr() try: self._attrs[node.name] except KeyError: raise xml.dom.NotFoundErr() _clear_id_cache(self) node.unlink() # Restore this since the node is still useful and otherwise # unlinked node.ownerDocument = self.ownerDocument removeAttributeNodeNS = removeAttributeNode def hasAttribute(self, name): if self._attrs is None: return False return name in self._attrs def hasAttributeNS(self, namespaceURI, localName): if self._attrsNS is None: return False return (namespaceURI, localName) in self._attrsNS def getElementsByTagName(self, name): return _get_elements_by_tagName_helper(self, name, NodeList()) def getElementsByTagNameNS(self, namespaceURI, localName): return _get_elements_by_tagName_ns_helper( self, namespaceURI, localName, NodeList()) def __repr__(self): return "" % (self.tagName, id(self)) def writexml(self, writer, indent="", addindent="", newl=""): # indent = current indentation # addindent = indentation to add to higher levels # newl = newline string writer.write(indent+"<" + self.tagName) attrs = self._get_attributes() a_names = sorted(attrs.keys()) for a_name in a_names: writer.write(" %s=\"" % a_name) _write_data(writer, attrs[a_name].value) writer.write("\"") if self.childNodes: writer.write(">") if (len(self.childNodes) == 1 and self.childNodes[0].nodeType == Node.TEXT_NODE): self.childNodes[0].writexml(writer, '', '', '') else: writer.write(newl) for node in self.childNodes: node.writexml(writer, indent+addindent, addindent, newl) writer.write(indent) writer.write("%s" % (self.tagName, newl)) else: writer.write("/>%s"%(newl)) def _get_attributes(self): self._ensure_attributes() return NamedNodeMap(self._attrs, self._attrsNS, self) def hasAttributes(self): if self._attrs: return True else: return False # DOM Level 3 attributes, based on the 22 Oct 2002 draft def setIdAttribute(self, name): idAttr = self.getAttributeNode(name) self.setIdAttributeNode(idAttr) def setIdAttributeNS(self, namespaceURI, localName): idAttr = self.getAttributeNodeNS(namespaceURI, localName) self.setIdAttributeNode(idAttr) def setIdAttributeNode(self, idAttr): if idAttr is None or not self.isSameNode(idAttr.ownerElement): raise xml.dom.NotFoundErr() if _get_containing_entref(self) is not None: raise xml.dom.NoModificationAllowedErr() if not idAttr._is_id: idAttr._is_id = True self._magic_id_nodes += 1 self.ownerDocument._magic_id_count += 1 _clear_id_cache(self) defproperty(Element, "attributes", doc="NamedNodeMap of attributes on the element.") defproperty(Element, "localName", doc="Namespace-local name of this element.") def _set_attribute_node(element, attr): _clear_id_cache(element) element._ensure_attributes() element._attrs[attr.name] = attr element._attrsNS[(attr.namespaceURI, attr.localName)] = attr # This creates a circular reference, but Element.unlink() # breaks the cycle since the references to the attribute # dictionaries are tossed. attr.ownerElement = element class Childless: """Mixin that makes childless-ness easy to implement and avoids the complexity of the Node methods that deal with children. """ __slots__ = () attributes = None childNodes = EmptyNodeList() firstChild = None lastChild = None def _get_firstChild(self): return None def _get_lastChild(self): return None def appendChild(self, node): raise xml.dom.HierarchyRequestErr( self.nodeName + " nodes cannot have children") def hasChildNodes(self): return False def insertBefore(self, newChild, refChild): raise xml.dom.HierarchyRequestErr( self.nodeName + " nodes do not have children") def removeChild(self, oldChild): raise xml.dom.NotFoundErr( self.nodeName + " nodes do not have children") def normalize(self): # For childless nodes, normalize() has nothing to do. pass def replaceChild(self, newChild, oldChild): raise xml.dom.HierarchyRequestErr( self.nodeName + " nodes do not have children") class ProcessingInstruction(Childless, Node): nodeType = Node.PROCESSING_INSTRUCTION_NODE __slots__ = ('target', 'data') def __init__(self, target, data): self.target = target self.data = data # nodeValue is an alias for data def _get_nodeValue(self): return self.data def _set_nodeValue(self, value): self.data = value nodeValue = property(_get_nodeValue, _set_nodeValue) # nodeName is an alias for target def _get_nodeName(self): return self.target def _set_nodeName(self, value): self.target = value nodeName = property(_get_nodeName, _set_nodeName) def writexml(self, writer, indent="", addindent="", newl=""): writer.write("%s%s" % (indent,self.target, self.data, newl)) class CharacterData(Childless, Node): __slots__=('_data', 'ownerDocument','parentNode', 'previousSibling', 'nextSibling') def __init__(self): self.ownerDocument = self.parentNode = None self.previousSibling = self.nextSibling = None self._data = '' Node.__init__(self) def _get_length(self): return len(self.data) __len__ = _get_length def _get_data(self): return self._data def _set_data(self, data): self._data = data data = nodeValue = property(_get_data, _set_data) def __repr__(self): data = self.data if len(data) > 10: dotdotdot = "..." else: dotdotdot = "" return '' % ( self.__class__.__name__, data[0:10], dotdotdot) def substringData(self, offset, count): if offset < 0: raise xml.dom.IndexSizeErr("offset cannot be negative") if offset >= len(self.data): raise xml.dom.IndexSizeErr("offset cannot be beyond end of data") if count < 0: raise xml.dom.IndexSizeErr("count cannot be negative") return self.data[offset:offset+count] def appendData(self, arg): self.data = self.data + arg def insertData(self, offset, arg): if offset < 0: raise xml.dom.IndexSizeErr("offset cannot be negative") if offset >= len(self.data): raise xml.dom.IndexSizeErr("offset cannot be beyond end of data") if arg: self.data = "%s%s%s" % ( self.data[:offset], arg, self.data[offset:]) def deleteData(self, offset, count): if offset < 0: raise xml.dom.IndexSizeErr("offset cannot be negative") if offset >= len(self.data): raise xml.dom.IndexSizeErr("offset cannot be beyond end of data") if count < 0: raise xml.dom.IndexSizeErr("count cannot be negative") if count: self.data = self.data[:offset] + self.data[offset+count:] def replaceData(self, offset, count, arg): if offset < 0: raise xml.dom.IndexSizeErr("offset cannot be negative") if offset >= len(self.data): raise xml.dom.IndexSizeErr("offset cannot be beyond end of data") if count < 0: raise xml.dom.IndexSizeErr("count cannot be negative") if count: self.data = "%s%s%s" % ( self.data[:offset], arg, self.data[offset+count:]) defproperty(CharacterData, "length", doc="Length of the string data.") class Text(CharacterData): __slots__ = () nodeType = Node.TEXT_NODE nodeName = "#text" attributes = None def splitText(self, offset): if offset < 0 or offset > len(self.data): raise xml.dom.IndexSizeErr("illegal offset value") newText = self.__class__() newText.data = self.data[offset:] newText.ownerDocument = self.ownerDocument next = self.nextSibling if self.parentNode and self in self.parentNode.childNodes: if next is None: self.parentNode.appendChild(newText) else: self.parentNode.insertBefore(newText, next) self.data = self.data[:offset] return newText def writexml(self, writer, indent="", addindent="", newl=""): _write_data(writer, "%s%s%s" % (indent, self.data, newl)) # DOM Level 3 (WD 9 April 2002) def _get_wholeText(self): L = [self.data] n = self.previousSibling while n is not None: if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE): L.insert(0, n.data) n = n.previousSibling else: break n = self.nextSibling while n is not None: if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE): L.append(n.data) n = n.nextSibling else: break return ''.join(L) def replaceWholeText(self, content): # XXX This needs to be seriously changed if minidom ever # supports EntityReference nodes. parent = self.parentNode n = self.previousSibling while n is not None: if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE): next = n.previousSibling parent.removeChild(n) n = next else: break n = self.nextSibling if not content: parent.removeChild(self) while n is not None: if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE): next = n.nextSibling parent.removeChild(n) n = next else: break if content: self.data = content return self else: return None def _get_isWhitespaceInElementContent(self): if self.data.strip(): return False elem = _get_containing_element(self) if elem is None: return False info = self.ownerDocument._get_elem_info(elem) if info is None: return False else: return info.isElementContent() defproperty(Text, "isWhitespaceInElementContent", doc="True iff this text node contains only whitespace" " and is in element content.") defproperty(Text, "wholeText", doc="The text of all logically-adjacent text nodes.") def _get_containing_element(node): c = node.parentNode while c is not None: if c.nodeType == Node.ELEMENT_NODE: return c c = c.parentNode return None def _get_containing_entref(node): c = node.parentNode while c is not None: if c.nodeType == Node.ENTITY_REFERENCE_NODE: return c c = c.parentNode return None class Comment(CharacterData): nodeType = Node.COMMENT_NODE nodeName = "#comment" def __init__(self, data): CharacterData.__init__(self) self._data = data def writexml(self, writer, indent="", addindent="", newl=""): if "--" in self.data: raise ValueError("'--' is not allowed in a comment node") writer.write("%s%s" % (indent, self.data, newl)) class CDATASection(Text): __slots__ = () nodeType = Node.CDATA_SECTION_NODE nodeName = "#cdata-section" def writexml(self, writer, indent="", addindent="", newl=""): if self.data.find("]]>") >= 0: raise ValueError("']]>' not allowed in a CDATA section") writer.write("" % self.data) class ReadOnlySequentialNamedNodeMap(object): __slots__ = '_seq', def __init__(self, seq=()): # seq should be a list or tuple self._seq = seq def __len__(self): return len(self._seq) def _get_length(self): return len(self._seq) def getNamedItem(self, name): for n in self._seq: if n.nodeName == name: return n def getNamedItemNS(self, namespaceURI, localName): for n in self._seq: if n.namespaceURI == namespaceURI and n.localName == localName: return n def __getitem__(self, name_or_tuple): if isinstance(name_or_tuple, tuple): node = self.getNamedItemNS(*name_or_tuple) else: node = self.getNamedItem(name_or_tuple) if node is None: raise KeyError(name_or_tuple) return node def item(self, index): if index < 0: return None try: return self._seq[index] except IndexError: return None def removeNamedItem(self, name): raise xml.dom.NoModificationAllowedErr( "NamedNodeMap instance is read-only") def removeNamedItemNS(self, namespaceURI, localName): raise xml.dom.NoModificationAllowedErr( "NamedNodeMap instance is read-only") def setNamedItem(self, node): raise xml.dom.NoModificationAllowedErr( "NamedNodeMap instance is read-only") def setNamedItemNS(self, node): raise xml.dom.NoModificationAllowedErr( "NamedNodeMap instance is read-only") def __getstate__(self): return [self._seq] def __setstate__(self, state): self._seq = state[0] defproperty(ReadOnlySequentialNamedNodeMap, "length", doc="Number of entries in the NamedNodeMap.") class Identified: """Mix-in class that supports the publicId and systemId attributes.""" __slots__ = 'publicId', 'systemId' def _identified_mixin_init(self, publicId, systemId): self.publicId = publicId self.systemId = systemId def _get_publicId(self): return self.publicId def _get_systemId(self): return self.systemId class DocumentType(Identified, Childless, Node): nodeType = Node.DOCUMENT_TYPE_NODE nodeValue = None name = None publicId = None systemId = None internalSubset = None def __init__(self, qualifiedName): self.entities = ReadOnlySequentialNamedNodeMap() self.notations = ReadOnlySequentialNamedNodeMap() if qualifiedName: prefix, localname = _nssplit(qualifiedName) self.name = localname self.nodeName = self.name def _get_internalSubset(self): return self.internalSubset def cloneNode(self, deep): if self.ownerDocument is None: # it's ok clone = DocumentType(None) clone.name = self.name clone.nodeName = self.name operation = xml.dom.UserDataHandler.NODE_CLONED if deep: clone.entities._seq = [] clone.notations._seq = [] for n in self.notations._seq: notation = Notation(n.nodeName, n.publicId, n.systemId) clone.notations._seq.append(notation) n._call_user_data_handler(operation, n, notation) for e in self.entities._seq: entity = Entity(e.nodeName, e.publicId, e.systemId, e.notationName) entity.actualEncoding = e.actualEncoding entity.encoding = e.encoding entity.version = e.version clone.entities._seq.append(entity) e._call_user_data_handler(operation, e, entity) self._call_user_data_handler(operation, self, clone) return clone else: return None def writexml(self, writer, indent="", addindent="", newl=""): writer.write(""+newl) class Entity(Identified, Node): attributes = None nodeType = Node.ENTITY_NODE nodeValue = None actualEncoding = None encoding = None version = None def __init__(self, name, publicId, systemId, notation): self.nodeName = name self.notationName = notation self.childNodes = NodeList() self._identified_mixin_init(publicId, systemId) def _get_actualEncoding(self): return self.actualEncoding def _get_encoding(self): return self.encoding def _get_version(self): return self.version def appendChild(self, newChild): raise xml.dom.HierarchyRequestErr( "cannot append children to an entity node") def insertBefore(self, newChild, refChild): raise xml.dom.HierarchyRequestErr( "cannot insert children below an entity node") def removeChild(self, oldChild): raise xml.dom.HierarchyRequestErr( "cannot remove children from an entity node") def replaceChild(self, newChild, oldChild): raise xml.dom.HierarchyRequestErr( "cannot replace children of an entity node") class Notation(Identified, Childless, Node): nodeType = Node.NOTATION_NODE nodeValue = None def __init__(self, name, publicId, systemId): self.nodeName = name self._identified_mixin_init(publicId, systemId) class DOMImplementation(DOMImplementationLS): _features = [("core", "1.0"), ("core", "2.0"), ("core", None), ("xml", "1.0"), ("xml", "2.0"), ("xml", None), ("ls-load", "3.0"), ("ls-load", None), ] def hasFeature(self, feature, version): if version == "": version = None return (feature.lower(), version) in self._features def createDocument(self, namespaceURI, qualifiedName, doctype): if doctype and doctype.parentNode is not None: raise xml.dom.WrongDocumentErr( "doctype object owned by another DOM tree") doc = self._create_document() add_root_element = not (namespaceURI is None and qualifiedName is None and doctype is None) if not qualifiedName and add_root_element: # The spec is unclear what to raise here; SyntaxErr # would be the other obvious candidate. Since Xerces raises # InvalidCharacterErr, and since SyntaxErr is not listed # for createDocument, that seems to be the better choice. # XXX: need to check for illegal characters here and in # createElement. # DOM Level III clears this up when talking about the return value # of this function. If namespaceURI, qName and DocType are # Null the document is returned without a document element # Otherwise if doctype or namespaceURI are not None # Then we go back to the above problem raise xml.dom.InvalidCharacterErr("Element with no name") if add_root_element: prefix, localname = _nssplit(qualifiedName) if prefix == "xml" \ and namespaceURI != "http://www.w3.org/XML/1998/namespace": raise xml.dom.NamespaceErr("illegal use of 'xml' prefix") if prefix and not namespaceURI: raise xml.dom.NamespaceErr( "illegal use of prefix without namespaces") element = doc.createElementNS(namespaceURI, qualifiedName) if doctype: doc.appendChild(doctype) doc.appendChild(element) if doctype: doctype.parentNode = doctype.ownerDocument = doc doc.doctype = doctype doc.implementation = self return doc def createDocumentType(self, qualifiedName, publicId, systemId): doctype = DocumentType(qualifiedName) doctype.publicId = publicId doctype.systemId = systemId return doctype # DOM Level 3 (WD 9 April 2002) def getInterface(self, feature): if self.hasFeature(feature, None): return self else: return None # internal def _create_document(self): return Document() class ElementInfo(object): """Object that represents content-model information for an element. This implementation is not expected to be used in practice; DOM builders should provide implementations which do the right thing using information available to it. """ __slots__ = 'tagName', def __init__(self, name): self.tagName = name def getAttributeType(self, aname): return _no_type def getAttributeTypeNS(self, namespaceURI, localName): return _no_type def isElementContent(self): return False def isEmpty(self): """Returns true iff this element is declared to have an EMPTY content model.""" return False def isId(self, aname): """Returns true iff the named attribute is a DTD-style ID.""" return False def isIdNS(self, namespaceURI, localName): """Returns true iff the identified attribute is a DTD-style ID.""" return False def __getstate__(self): return self.tagName def __setstate__(self, state): self.tagName = state def _clear_id_cache(node): if node.nodeType == Node.DOCUMENT_NODE: node._id_cache.clear() node._id_search_stack = None elif _in_document(node): node.ownerDocument._id_cache.clear() node.ownerDocument._id_search_stack= None class Document(Node, DocumentLS): __slots__ = ('_elem_info', 'doctype', '_id_search_stack', 'childNodes', '_id_cache') _child_node_types = (Node.ELEMENT_NODE, Node.PROCESSING_INSTRUCTION_NODE, Node.COMMENT_NODE, Node.DOCUMENT_TYPE_NODE) implementation = DOMImplementation() nodeType = Node.DOCUMENT_NODE nodeName = "#document" nodeValue = None attributes = None parentNode = None previousSibling = nextSibling = None # Document attributes from Level 3 (WD 9 April 2002) actualEncoding = None encoding = None standalone = None version = None strictErrorChecking = False errorHandler = None documentURI = None _magic_id_count = 0 def __init__(self): self.doctype = None self.childNodes = NodeList() # mapping of (namespaceURI, localName) -> ElementInfo # and tagName -> ElementInfo self._elem_info = {} self._id_cache = {} self._id_search_stack = None def _get_elem_info(self, element): if element.namespaceURI: key = element.namespaceURI, element.localName else: key = element.tagName return self._elem_info.get(key) def _get_actualEncoding(self): return self.actualEncoding def _get_doctype(self): return self.doctype def _get_documentURI(self): return self.documentURI def _get_encoding(self): return self.encoding def _get_errorHandler(self): return self.errorHandler def _get_standalone(self): return self.standalone def _get_strictErrorChecking(self): return self.strictErrorChecking def _get_version(self): return self.version def appendChild(self, node): if node.nodeType not in self._child_node_types: raise xml.dom.HierarchyRequestErr( "%s cannot be child of %s" % (repr(node), repr(self))) if node.parentNode is not None: # This needs to be done before the next test since this # may *be* the document element, in which case it should # end up re-ordered to the end. node.parentNode.removeChild(node) if node.nodeType == Node.ELEMENT_NODE \ and self._get_documentElement(): raise xml.dom.HierarchyRequestErr( "two document elements disallowed") return Node.appendChild(self, node) def removeChild(self, oldChild): try: self.childNodes.remove(oldChild) except ValueError: raise xml.dom.NotFoundErr() oldChild.nextSibling = oldChild.previousSibling = None oldChild.parentNode = None if self.documentElement is oldChild: self.documentElement = None return oldChild def _get_documentElement(self): for node in self.childNodes: if node.nodeType == Node.ELEMENT_NODE: return node def unlink(self): if self.doctype is not None: self.doctype.unlink() self.doctype = None Node.unlink(self) def cloneNode(self, deep): if not deep: return None clone = self.implementation.createDocument(None, None, None) clone.encoding = self.encoding clone.standalone = self.standalone clone.version = self.version for n in self.childNodes: childclone = _clone_node(n, deep, clone) assert childclone.ownerDocument.isSameNode(clone) clone.childNodes.append(childclone) if childclone.nodeType == Node.DOCUMENT_NODE: assert clone.documentElement is None elif childclone.nodeType == Node.DOCUMENT_TYPE_NODE: assert clone.doctype is None clone.doctype = childclone childclone.parentNode = clone self._call_user_data_handler(xml.dom.UserDataHandler.NODE_CLONED, self, clone) return clone def createDocumentFragment(self): d = DocumentFragment() d.ownerDocument = self return d def createElement(self, tagName): e = Element(tagName) e.ownerDocument = self return e def createTextNode(self, data): if not isinstance(data, str): raise TypeError("node contents must be a string") t = Text() t.data = data t.ownerDocument = self return t def createCDATASection(self, data): if not isinstance(data, str): raise TypeError("node contents must be a string") c = CDATASection() c.data = data c.ownerDocument = self return c def createComment(self, data): c = Comment(data) c.ownerDocument = self return c def createProcessingInstruction(self, target, data): p = ProcessingInstruction(target, data) p.ownerDocument = self return p def createAttribute(self, qName): a = Attr(qName) a.ownerDocument = self a.value = "" return a def createElementNS(self, namespaceURI, qualifiedName): prefix, localName = _nssplit(qualifiedName) e = Element(qualifiedName, namespaceURI, prefix) e.ownerDocument = self return e def createAttributeNS(self, namespaceURI, qualifiedName): prefix, localName = _nssplit(qualifiedName) a = Attr(qualifiedName, namespaceURI, localName, prefix) a.ownerDocument = self a.value = "" return a # A couple of implementation-specific helpers to create node types # not supported by the W3C DOM specs: def _create_entity(self, name, publicId, systemId, notationName): e = Entity(name, publicId, systemId, notationName) e.ownerDocument = self return e def _create_notation(self, name, publicId, systemId): n = Notation(name, publicId, systemId) n.ownerDocument = self return n def getElementById(self, id): if id in self._id_cache: return self._id_cache[id] if not (self._elem_info or self._magic_id_count): return None stack = self._id_search_stack if stack is None: # we never searched before, or the cache has been cleared stack = [self.documentElement] self._id_search_stack = stack elif not stack: # Previous search was completed and cache is still valid; # no matching node. return None result = None while stack: node = stack.pop() # add child elements to stack for continued searching stack.extend([child for child in node.childNodes if child.nodeType in _nodeTypes_with_children]) # check this node info = self._get_elem_info(node) if info: # We have to process all ID attributes before # returning in order to get all the attributes set to # be IDs using Element.setIdAttribute*(). for attr in node.attributes.values(): if attr.namespaceURI: if info.isIdNS(attr.namespaceURI, attr.localName): self._id_cache[attr.value] = node if attr.value == id: result = node elif not node._magic_id_nodes: break elif info.isId(attr.name): self._id_cache[attr.value] = node if attr.value == id: result = node elif not node._magic_id_nodes: break elif attr._is_id: self._id_cache[attr.value] = node if attr.value == id: result = node elif node._magic_id_nodes == 1: break elif node._magic_id_nodes: for attr in node.attributes.values(): if attr._is_id: self._id_cache[attr.value] = node if attr.value == id: result = node if result is not None: break return result def getElementsByTagName(self, name): return _get_elements_by_tagName_helper(self, name, NodeList()) def getElementsByTagNameNS(self, namespaceURI, localName): return _get_elements_by_tagName_ns_helper( self, namespaceURI, localName, NodeList()) def isSupported(self, feature, version): return self.implementation.hasFeature(feature, version) def importNode(self, node, deep): if node.nodeType == Node.DOCUMENT_NODE: raise xml.dom.NotSupportedErr("cannot import document nodes") elif node.nodeType == Node.DOCUMENT_TYPE_NODE: raise xml.dom.NotSupportedErr("cannot import document type nodes") return _clone_node(node, deep, self) def writexml(self, writer, indent="", addindent="", newl="", encoding=None): if encoding is None: writer.write(''+newl) else: writer.write('%s' % ( encoding, newl)) for node in self.childNodes: node.writexml(writer, indent, addindent, newl) # DOM Level 3 (WD 9 April 2002) def renameNode(self, n, namespaceURI, name): if n.ownerDocument is not self: raise xml.dom.WrongDocumentErr( "cannot rename nodes from other documents;\n" "expected %s,\nfound %s" % (self, n.ownerDocument)) if n.nodeType not in (Node.ELEMENT_NODE, Node.ATTRIBUTE_NODE): raise xml.dom.NotSupportedErr( "renameNode() only applies to element and attribute nodes") if namespaceURI != EMPTY_NAMESPACE: if ':' in name: prefix, localName = name.split(':', 1) if ( prefix == "xmlns" and namespaceURI != xml.dom.XMLNS_NAMESPACE): raise xml.dom.NamespaceErr( "illegal use of 'xmlns' prefix") else: if ( name == "xmlns" and namespaceURI != xml.dom.XMLNS_NAMESPACE and n.nodeType == Node.ATTRIBUTE_NODE): raise xml.dom.NamespaceErr( "illegal use of the 'xmlns' attribute") prefix = None localName = name else: prefix = None localName = None if n.nodeType == Node.ATTRIBUTE_NODE: element = n.ownerElement if element is not None: is_id = n._is_id element.removeAttributeNode(n) else: element = None n.prefix = prefix n._localName = localName n.namespaceURI = namespaceURI n.nodeName = name if n.nodeType == Node.ELEMENT_NODE: n.tagName = name else: # attribute node n.name = name if element is not None: element.setAttributeNode(n) if is_id: element.setIdAttributeNode(n) # It's not clear from a semantic perspective whether we should # call the user data handlers for the NODE_RENAMED event since # we're re-using the existing node. The draft spec has been # interpreted as meaning "no, don't call the handler unless a # new node is created." return n defproperty(Document, "documentElement", doc="Top-level element of this document.") def _clone_node(node, deep, newOwnerDocument): """ Clone a node and give it the new owner document. Called by Node.cloneNode and Document.importNode """ if node.ownerDocument.isSameNode(newOwnerDocument): operation = xml.dom.UserDataHandler.NODE_CLONED else: operation = xml.dom.UserDataHandler.NODE_IMPORTED if node.nodeType == Node.ELEMENT_NODE: clone = newOwnerDocument.createElementNS(node.namespaceURI, node.nodeName) for attr in node.attributes.values(): clone.setAttributeNS(attr.namespaceURI, attr.nodeName, attr.value) a = clone.getAttributeNodeNS(attr.namespaceURI, attr.localName) a.specified = attr.specified if deep: for child in node.childNodes: c = _clone_node(child, deep, newOwnerDocument) clone.appendChild(c) elif node.nodeType == Node.DOCUMENT_FRAGMENT_NODE: clone = newOwnerDocument.createDocumentFragment() if deep: for child in node.childNodes: c = _clone_node(child, deep, newOwnerDocument) clone.appendChild(c) elif node.nodeType == Node.TEXT_NODE: clone = newOwnerDocument.createTextNode(node.data) elif node.nodeType == Node.CDATA_SECTION_NODE: clone = newOwnerDocument.createCDATASection(node.data) elif node.nodeType == Node.PROCESSING_INSTRUCTION_NODE: clone = newOwnerDocument.createProcessingInstruction(node.target, node.data) elif node.nodeType == Node.COMMENT_NODE: clone = newOwnerDocument.createComment(node.data) elif node.nodeType == Node.ATTRIBUTE_NODE: clone = newOwnerDocument.createAttributeNS(node.namespaceURI, node.nodeName) clone.specified = True clone.value = node.value elif node.nodeType == Node.DOCUMENT_TYPE_NODE: assert node.ownerDocument is not newOwnerDocument operation = xml.dom.UserDataHandler.NODE_IMPORTED clone = newOwnerDocument.implementation.createDocumentType( node.name, node.publicId, node.systemId) clone.ownerDocument = newOwnerDocument if deep: clone.entities._seq = [] clone.notations._seq = [] for n in node.notations._seq: notation = Notation(n.nodeName, n.publicId, n.systemId) notation.ownerDocument = newOwnerDocument clone.notations._seq.append(notation) if hasattr(n, '_call_user_data_handler'): n._call_user_data_handler(operation, n, notation) for e in node.entities._seq: entity = Entity(e.nodeName, e.publicId, e.systemId, e.notationName) entity.actualEncoding = e.actualEncoding entity.encoding = e.encoding entity.version = e.version entity.ownerDocument = newOwnerDocument clone.entities._seq.append(entity) if hasattr(e, '_call_user_data_handler'): e._call_user_data_handler(operation, e, entity) else: # Note the cloning of Document and DocumentType nodes is # implementation specific. minidom handles those cases # directly in the cloneNode() methods. raise xml.dom.NotSupportedErr("Cannot clone node %s" % repr(node)) # Check for _call_user_data_handler() since this could conceivably # used with other DOM implementations (one of the FourThought # DOMs, perhaps?). if hasattr(node, '_call_user_data_handler'): node._call_user_data_handler(operation, node, clone) return clone def _nssplit(qualifiedName): fields = qualifiedName.split(':', 1) if len(fields) == 2: return fields else: return (None, fields[0]) def _do_pulldom_parse(func, args, kwargs): events = func(*args, **kwargs) toktype, rootNode = events.getEvent() events.expandNode(rootNode) events.clear() return rootNode def parse(file, parser=None, bufsize=None): """Parse a file into a DOM by filename or file object.""" if parser is None and not bufsize: from xml.dom import expatbuilder return expatbuilder.parse(file) else: from xml.dom import pulldom return _do_pulldom_parse(pulldom.parse, (file,), {'parser': parser, 'bufsize': bufsize}) def parseString(string, parser=None): """Parse a file into a DOM from a string.""" if parser is None: from xml.dom import expatbuilder return expatbuilder.parseString(string) else: from xml.dom import pulldom return _do_pulldom_parse(pulldom.parseString, (string,), {'parser': parser}) def getDOMImplementation(features=None): if features: if isinstance(features, str): features = domreg._parse_feature_string(features) for f, v in features: if not Document.implementation.hasFeature(f, v): return None return Document.implementation pulldom.py000064400000026761147204745200006613 0ustar00import xml.sax import xml.sax.handler START_ELEMENT = "START_ELEMENT" END_ELEMENT = "END_ELEMENT" COMMENT = "COMMENT" START_DOCUMENT = "START_DOCUMENT" END_DOCUMENT = "END_DOCUMENT" PROCESSING_INSTRUCTION = "PROCESSING_INSTRUCTION" IGNORABLE_WHITESPACE = "IGNORABLE_WHITESPACE" CHARACTERS = "CHARACTERS" class PullDOM(xml.sax.ContentHandler): _locator = None document = None def __init__(self, documentFactory=None): from xml.dom import XML_NAMESPACE self.documentFactory = documentFactory self.firstEvent = [None, None] self.lastEvent = self.firstEvent self.elementStack = [] self.push = self.elementStack.append try: self.pop = self.elementStack.pop except AttributeError: # use class' pop instead pass self._ns_contexts = [{XML_NAMESPACE:'xml'}] # contains uri -> prefix dicts self._current_context = self._ns_contexts[-1] self.pending_events = [] def pop(self): result = self.elementStack[-1] del self.elementStack[-1] return result def setDocumentLocator(self, locator): self._locator = locator def startPrefixMapping(self, prefix, uri): if not hasattr(self, '_xmlns_attrs'): self._xmlns_attrs = [] self._xmlns_attrs.append((prefix or 'xmlns', uri)) self._ns_contexts.append(self._current_context.copy()) self._current_context[uri] = prefix or None def endPrefixMapping(self, prefix): self._current_context = self._ns_contexts.pop() def startElementNS(self, name, tagName , attrs): # Retrieve xml namespace declaration attributes. xmlns_uri = 'http://www.w3.org/2000/xmlns/' xmlns_attrs = getattr(self, '_xmlns_attrs', None) if xmlns_attrs is not None: for aname, value in xmlns_attrs: attrs._attrs[(xmlns_uri, aname)] = value self._xmlns_attrs = [] uri, localname = name if uri: # When using namespaces, the reader may or may not # provide us with the original name. If not, create # *a* valid tagName from the current context. if tagName is None: prefix = self._current_context[uri] if prefix: tagName = prefix + ":" + localname else: tagName = localname if self.document: node = self.document.createElementNS(uri, tagName) else: node = self.buildDocument(uri, tagName) else: # When the tagname is not prefixed, it just appears as # localname if self.document: node = self.document.createElement(localname) else: node = self.buildDocument(None, localname) for aname,value in attrs.items(): a_uri, a_localname = aname if a_uri == xmlns_uri: if a_localname == 'xmlns': qname = a_localname else: qname = 'xmlns:' + a_localname attr = self.document.createAttributeNS(a_uri, qname) node.setAttributeNodeNS(attr) elif a_uri: prefix = self._current_context[a_uri] if prefix: qname = prefix + ":" + a_localname else: qname = a_localname attr = self.document.createAttributeNS(a_uri, qname) node.setAttributeNodeNS(attr) else: attr = self.document.createAttribute(a_localname) node.setAttributeNode(attr) attr.value = value self.lastEvent[1] = [(START_ELEMENT, node), None] self.lastEvent = self.lastEvent[1] self.push(node) def endElementNS(self, name, tagName): self.lastEvent[1] = [(END_ELEMENT, self.pop()), None] self.lastEvent = self.lastEvent[1] def startElement(self, name, attrs): if self.document: node = self.document.createElement(name) else: node = self.buildDocument(None, name) for aname,value in attrs.items(): attr = self.document.createAttribute(aname) attr.value = value node.setAttributeNode(attr) self.lastEvent[1] = [(START_ELEMENT, node), None] self.lastEvent = self.lastEvent[1] self.push(node) def endElement(self, name): self.lastEvent[1] = [(END_ELEMENT, self.pop()), None] self.lastEvent = self.lastEvent[1] def comment(self, s): if self.document: node = self.document.createComment(s) self.lastEvent[1] = [(COMMENT, node), None] self.lastEvent = self.lastEvent[1] else: event = [(COMMENT, s), None] self.pending_events.append(event) def processingInstruction(self, target, data): if self.document: node = self.document.createProcessingInstruction(target, data) self.lastEvent[1] = [(PROCESSING_INSTRUCTION, node), None] self.lastEvent = self.lastEvent[1] else: event = [(PROCESSING_INSTRUCTION, target, data), None] self.pending_events.append(event) def ignorableWhitespace(self, chars): node = self.document.createTextNode(chars) self.lastEvent[1] = [(IGNORABLE_WHITESPACE, node), None] self.lastEvent = self.lastEvent[1] def characters(self, chars): node = self.document.createTextNode(chars) self.lastEvent[1] = [(CHARACTERS, node), None] self.lastEvent = self.lastEvent[1] def startDocument(self): if self.documentFactory is None: import xml.dom.minidom self.documentFactory = xml.dom.minidom.Document.implementation def buildDocument(self, uri, tagname): # Can't do that in startDocument, since we need the tagname # XXX: obtain DocumentType node = self.documentFactory.createDocument(uri, tagname, None) self.document = node self.lastEvent[1] = [(START_DOCUMENT, node), None] self.lastEvent = self.lastEvent[1] self.push(node) # Put everything we have seen so far into the document for e in self.pending_events: if e[0][0] == PROCESSING_INSTRUCTION: _,target,data = e[0] n = self.document.createProcessingInstruction(target, data) e[0] = (PROCESSING_INSTRUCTION, n) elif e[0][0] == COMMENT: n = self.document.createComment(e[0][1]) e[0] = (COMMENT, n) else: raise AssertionError("Unknown pending event ",e[0][0]) self.lastEvent[1] = e self.lastEvent = e self.pending_events = None return node.firstChild def endDocument(self): self.lastEvent[1] = [(END_DOCUMENT, self.document), None] self.pop() def clear(self): "clear(): Explicitly release parsing structures" self.document = None class ErrorHandler: def warning(self, exception): print(exception) def error(self, exception): raise exception def fatalError(self, exception): raise exception class DOMEventStream: def __init__(self, stream, parser, bufsize): self.stream = stream self.parser = parser self.bufsize = bufsize if not hasattr(self.parser, 'feed'): self.getEvent = self._slurp self.reset() def reset(self): self.pulldom = PullDOM() # This content handler relies on namespace support self.parser.setFeature(xml.sax.handler.feature_namespaces, 1) self.parser.setContentHandler(self.pulldom) def __getitem__(self, pos): rc = self.getEvent() if rc: return rc raise IndexError def __next__(self): rc = self.getEvent() if rc: return rc raise StopIteration def __iter__(self): return self def expandNode(self, node): event = self.getEvent() parents = [node] while event: token, cur_node = event if cur_node is node: return if token != END_ELEMENT: parents[-1].appendChild(cur_node) if token == START_ELEMENT: parents.append(cur_node) elif token == END_ELEMENT: del parents[-1] event = self.getEvent() def getEvent(self): # use IncrementalParser interface, so we get the desired # pull effect if not self.pulldom.firstEvent[1]: self.pulldom.lastEvent = self.pulldom.firstEvent while not self.pulldom.firstEvent[1]: buf = self.stream.read(self.bufsize) if not buf: self.parser.close() return None self.parser.feed(buf) rc = self.pulldom.firstEvent[1][0] self.pulldom.firstEvent[1] = self.pulldom.firstEvent[1][1] return rc def _slurp(self): """ Fallback replacement for getEvent() using the standard SAX2 interface, which means we slurp the SAX events into memory (no performance gain, but we are compatible to all SAX parsers). """ self.parser.parse(self.stream) self.getEvent = self._emit return self._emit() def _emit(self): """ Fallback replacement for getEvent() that emits the events that _slurp() read previously. """ rc = self.pulldom.firstEvent[1][0] self.pulldom.firstEvent[1] = self.pulldom.firstEvent[1][1] return rc def clear(self): """clear(): Explicitly release parsing objects""" self.pulldom.clear() del self.pulldom self.parser = None self.stream = None class SAX2DOM(PullDOM): def startElementNS(self, name, tagName , attrs): PullDOM.startElementNS(self, name, tagName, attrs) curNode = self.elementStack[-1] parentNode = self.elementStack[-2] parentNode.appendChild(curNode) def startElement(self, name, attrs): PullDOM.startElement(self, name, attrs) curNode = self.elementStack[-1] parentNode = self.elementStack[-2] parentNode.appendChild(curNode) def processingInstruction(self, target, data): PullDOM.processingInstruction(self, target, data) node = self.lastEvent[0][1] parentNode = self.elementStack[-1] parentNode.appendChild(node) def ignorableWhitespace(self, chars): PullDOM.ignorableWhitespace(self, chars) node = self.lastEvent[0][1] parentNode = self.elementStack[-1] parentNode.appendChild(node) def characters(self, chars): PullDOM.characters(self, chars) node = self.lastEvent[0][1] parentNode = self.elementStack[-1] parentNode.appendChild(node) default_bufsize = (2 ** 14) - 20 def parse(stream_or_string, parser=None, bufsize=None): if bufsize is None: bufsize = default_bufsize if isinstance(stream_or_string, str): stream = open(stream_or_string, 'rb') else: stream = stream_or_string if not parser: parser = xml.sax.make_parser() return DOMEventStream(stream, parser, bufsize) def parseString(string, parser=None): from io import StringIO bufsize = len(string) buf = StringIO(string) if not parser: parser = xml.sax.make_parser() return DOMEventStream(buf, parser, bufsize) xmlbuilder.py000064400000031304147204745200007273 0ustar00"""Implementation of the DOM Level 3 'LS-Load' feature.""" import copy import warnings import xml.dom from xml.dom.NodeFilter import NodeFilter __all__ = ["DOMBuilder", "DOMEntityResolver", "DOMInputSource"] class Options: """Features object that has variables set for each DOMBuilder feature. The DOMBuilder class uses an instance of this class to pass settings to the ExpatBuilder class. """ # Note that the DOMBuilder class in LoadSave constrains which of these # values can be set using the DOM Level 3 LoadSave feature. namespaces = 1 namespace_declarations = True validation = False external_parameter_entities = True external_general_entities = True external_dtd_subset = True validate_if_schema = False validate = False datatype_normalization = False create_entity_ref_nodes = True entities = True whitespace_in_element_content = True cdata_sections = True comments = True charset_overrides_xml_encoding = True infoset = False supported_mediatypes_only = False errorHandler = None filter = None class DOMBuilder: entityResolver = None errorHandler = None filter = None ACTION_REPLACE = 1 ACTION_APPEND_AS_CHILDREN = 2 ACTION_INSERT_AFTER = 3 ACTION_INSERT_BEFORE = 4 _legal_actions = (ACTION_REPLACE, ACTION_APPEND_AS_CHILDREN, ACTION_INSERT_AFTER, ACTION_INSERT_BEFORE) def __init__(self): self._options = Options() def _get_entityResolver(self): return self.entityResolver def _set_entityResolver(self, entityResolver): self.entityResolver = entityResolver def _get_errorHandler(self): return self.errorHandler def _set_errorHandler(self, errorHandler): self.errorHandler = errorHandler def _get_filter(self): return self.filter def _set_filter(self, filter): self.filter = filter def setFeature(self, name, state): if self.supportsFeature(name): state = state and 1 or 0 try: settings = self._settings[(_name_xform(name), state)] except KeyError: raise xml.dom.NotSupportedErr( "unsupported feature: %r" % (name,)) else: for name, value in settings: setattr(self._options, name, value) else: raise xml.dom.NotFoundErr("unknown feature: " + repr(name)) def supportsFeature(self, name): return hasattr(self._options, _name_xform(name)) def canSetFeature(self, name, state): key = (_name_xform(name), state and 1 or 0) return key in self._settings # This dictionary maps from (feature,value) to a list of # (option,value) pairs that should be set on the Options object. # If a (feature,value) setting is not in this dictionary, it is # not supported by the DOMBuilder. # _settings = { ("namespace_declarations", 0): [ ("namespace_declarations", 0)], ("namespace_declarations", 1): [ ("namespace_declarations", 1)], ("validation", 0): [ ("validation", 0)], ("external_general_entities", 0): [ ("external_general_entities", 0)], ("external_general_entities", 1): [ ("external_general_entities", 1)], ("external_parameter_entities", 0): [ ("external_parameter_entities", 0)], ("external_parameter_entities", 1): [ ("external_parameter_entities", 1)], ("validate_if_schema", 0): [ ("validate_if_schema", 0)], ("create_entity_ref_nodes", 0): [ ("create_entity_ref_nodes", 0)], ("create_entity_ref_nodes", 1): [ ("create_entity_ref_nodes", 1)], ("entities", 0): [ ("create_entity_ref_nodes", 0), ("entities", 0)], ("entities", 1): [ ("entities", 1)], ("whitespace_in_element_content", 0): [ ("whitespace_in_element_content", 0)], ("whitespace_in_element_content", 1): [ ("whitespace_in_element_content", 1)], ("cdata_sections", 0): [ ("cdata_sections", 0)], ("cdata_sections", 1): [ ("cdata_sections", 1)], ("comments", 0): [ ("comments", 0)], ("comments", 1): [ ("comments", 1)], ("charset_overrides_xml_encoding", 0): [ ("charset_overrides_xml_encoding", 0)], ("charset_overrides_xml_encoding", 1): [ ("charset_overrides_xml_encoding", 1)], ("infoset", 0): [], ("infoset", 1): [ ("namespace_declarations", 0), ("validate_if_schema", 0), ("create_entity_ref_nodes", 0), ("entities", 0), ("cdata_sections", 0), ("datatype_normalization", 1), ("whitespace_in_element_content", 1), ("comments", 1), ("charset_overrides_xml_encoding", 1)], ("supported_mediatypes_only", 0): [ ("supported_mediatypes_only", 0)], ("namespaces", 0): [ ("namespaces", 0)], ("namespaces", 1): [ ("namespaces", 1)], } def getFeature(self, name): xname = _name_xform(name) try: return getattr(self._options, xname) except AttributeError: if name == "infoset": options = self._options return (options.datatype_normalization and options.whitespace_in_element_content and options.comments and options.charset_overrides_xml_encoding and not (options.namespace_declarations or options.validate_if_schema or options.create_entity_ref_nodes or options.entities or options.cdata_sections)) raise xml.dom.NotFoundErr("feature %s not known" % repr(name)) def parseURI(self, uri): if self.entityResolver: input = self.entityResolver.resolveEntity(None, uri) else: input = DOMEntityResolver().resolveEntity(None, uri) return self.parse(input) def parse(self, input): options = copy.copy(self._options) options.filter = self.filter options.errorHandler = self.errorHandler fp = input.byteStream if fp is None and options.systemId: import urllib.request fp = urllib.request.urlopen(input.systemId) return self._parse_bytestream(fp, options) def parseWithContext(self, input, cnode, action): if action not in self._legal_actions: raise ValueError("not a legal action") raise NotImplementedError("Haven't written this yet...") def _parse_bytestream(self, stream, options): import xml.dom.expatbuilder builder = xml.dom.expatbuilder.makeBuilder(options) return builder.parseFile(stream) def _name_xform(name): return name.lower().replace('-', '_') class DOMEntityResolver(object): __slots__ = '_opener', def resolveEntity(self, publicId, systemId): assert systemId is not None source = DOMInputSource() source.publicId = publicId source.systemId = systemId source.byteStream = self._get_opener().open(systemId) # determine the encoding if the transport provided it source.encoding = self._guess_media_encoding(source) # determine the base URI is we can import posixpath, urllib.parse parts = urllib.parse.urlparse(systemId) scheme, netloc, path, params, query, fragment = parts # XXX should we check the scheme here as well? if path and not path.endswith("/"): path = posixpath.dirname(path) + "/" parts = scheme, netloc, path, params, query, fragment source.baseURI = urllib.parse.urlunparse(parts) return source def _get_opener(self): try: return self._opener except AttributeError: self._opener = self._create_opener() return self._opener def _create_opener(self): import urllib.request return urllib.request.build_opener() def _guess_media_encoding(self, source): info = source.byteStream.info() if "Content-Type" in info: for param in info.getplist(): if param.startswith("charset="): return param.split("=", 1)[1].lower() class DOMInputSource(object): __slots__ = ('byteStream', 'characterStream', 'stringData', 'encoding', 'publicId', 'systemId', 'baseURI') def __init__(self): self.byteStream = None self.characterStream = None self.stringData = None self.encoding = None self.publicId = None self.systemId = None self.baseURI = None def _get_byteStream(self): return self.byteStream def _set_byteStream(self, byteStream): self.byteStream = byteStream def _get_characterStream(self): return self.characterStream def _set_characterStream(self, characterStream): self.characterStream = characterStream def _get_stringData(self): return self.stringData def _set_stringData(self, data): self.stringData = data def _get_encoding(self): return self.encoding def _set_encoding(self, encoding): self.encoding = encoding def _get_publicId(self): return self.publicId def _set_publicId(self, publicId): self.publicId = publicId def _get_systemId(self): return self.systemId def _set_systemId(self, systemId): self.systemId = systemId def _get_baseURI(self): return self.baseURI def _set_baseURI(self, uri): self.baseURI = uri class DOMBuilderFilter: """Element filter which can be used to tailor construction of a DOM instance. """ # There's really no need for this class; concrete implementations # should just implement the endElement() and startElement() # methods as appropriate. Using this makes it easy to only # implement one of them. FILTER_ACCEPT = 1 FILTER_REJECT = 2 FILTER_SKIP = 3 FILTER_INTERRUPT = 4 whatToShow = NodeFilter.SHOW_ALL def _get_whatToShow(self): return self.whatToShow def acceptNode(self, element): return self.FILTER_ACCEPT def startContainer(self, element): return self.FILTER_ACCEPT del NodeFilter class _AsyncDeprecatedProperty: def warn(self, cls): clsname = cls.__name__ warnings.warn( "{cls}.async is deprecated; use {cls}.async_".format(cls=clsname), DeprecationWarning) def __get__(self, instance, cls): self.warn(cls) if instance is not None: return instance.async_ return False def __set__(self, instance, value): self.warn(type(instance)) setattr(instance, 'async_', value) class DocumentLS: """Mixin to create documents that conform to the load/save spec.""" async_ = False locals()['async'] = _AsyncDeprecatedProperty() # Avoid DeprecationWarning def _get_async(self): return False def _set_async(self, flag): if flag: raise xml.dom.NotSupportedErr( "asynchronous document loading is not supported") def abort(self): # What does it mean to "clear" a document? Does the # documentElement disappear? raise NotImplementedError( "haven't figured out what this means yet") def load(self, uri): raise NotImplementedError("haven't written this yet") def loadXML(self, source): raise NotImplementedError("haven't written this yet") def saveXML(self, snode): if snode is None: snode = self elif snode.ownerDocument is not self: raise xml.dom.WrongDocumentErr() return snode.toxml() del _AsyncDeprecatedProperty class DOMImplementationLS: MODE_SYNCHRONOUS = 1 MODE_ASYNCHRONOUS = 2 def createDOMBuilder(self, mode, schemaType): if schemaType is not None: raise xml.dom.NotSupportedErr( "schemaType not yet supported") if mode == self.MODE_SYNCHRONOUS: return DOMBuilder() if mode == self.MODE_ASYNCHRONOUS: raise xml.dom.NotSupportedErr( "asynchronous builders are not supported") raise ValueError("unknown value for mode") def createDOMWriter(self): raise NotImplementedError( "the writer interface hasn't been written yet!") def createDOMInputSource(self): return DOMInputSource()