Ϫfs>dZddlmZddlmZmZmZddlmZdZ ddiZ Gdd Z e Z dd Z d Zd Zd ZdZGddeZGddZGddeZeeGddZGddeZdZGddej4ZGddZy) z DOM-like XML processing support. This module provides support for parsing XML into DOM-like object structures and serializing such structures to an XML string representation, optimized for use in streaming XML applications. )cast) Attribute Interface implementer)suxcT|jdd}t|dk(r|Sd|dfS)zSInternal method for splitting a prefixed Element name into its respective parts:Nr)splitlen)namentoks ;/usr/lib/python3/dist-packages/twisted/words/xish/domish.py _splitPrefixrs2 ::c1 D 4yA~ d1gz$http://www.w3.org/XML/1998/namespacexmlc2eZdZdZddZdZdZdZd dZy) _ListSerializerz=Internal class which serializes an Element tree into a bufferNcg|_i|_|r|jj||jjttj g|xsgz|_d|_yNr) writelistprefixesupdate G_PREFIXESvalues prefixStack prefixCounter)selfrprefixesInScopes r__init__z_ListSerializer.__init__'s]  MM  * Z(&--/0O4IrJrc8dj|jS)N)joinrrs rgetValuez_ListSerializer.getValue0swwt~~&&rc||jvr0d|jz|j|<|jdz|_|j|S)Nzxn%dr )rrruris r getPrefixz_ListSerializer.getPrefix3sI dmm #!'4+=+=!>DMM# !%!3!3a!7D }}S!!rc|j}tdt|jdzdzdD] }|||vs yy)Nr TFrranger rprefixstackis r prefixInScopez_ListSerializer.prefixInScope9sN  rC 0 01A5;R@ Aq! rc |jj}t|tr ||yt|tr|t |y|j }|j}|j|}}|jjD]\}} ||j| <|jjt|jj||}||}d} ||k7s||jvr"|j|} |j!| } | s |d|zn?|d| d| s/|d| d|d|jdj| d} ||k7r||k7s| r s |d |z|jjD]\}} |d|d| d|j"jD]\} } t| t$rq| \}}|j|}|j!|s-|d|d|d|jdj||d |d|dt | d d|d | dt | d d|d k(r |d yt'|j(d kDrJ|d |j(D]}|j+||| s |d|zn|d| d|d n|d|jj-y)Nz<%s) defaultUrizz)rappend isinstance SerializedXMLstr escapeToXmlrr)r9 localPrefixesitemsrrlistkeysr*r3 attributestupler children serializepop)relem closeElementr9writerr)currentDefaultUripur0inScopekvattr_uri attr_name attr_prefixcs rrFz_ListSerializer.serialize@s%% dM * $K  dC +d# $ yyhh(,% &&,,. !DAq DMM!  ! T%7%7%<%<%> ?@  *J ;C * t}} 4^^C(F((0G %4. ! AfXQtf% &xr#a01  $++F3 * * : V7 -:. /&&,,. 'DAq GA3b1% & 'OO))+ 5DAq!U#&'#)"nnX6 ))+6GK=8*A>?$$R(// <+a {"[A5F4GqIJ!B{1a0134 5 1  #J  t}}  ! #J]] 9qZ8 9g&'6(!D6+, $K rNN)r r#) __name__ __module__ __qualname____doc__r!r&r*r3rFrrrr$sG'" Yrrc|jdd}|jdd}|jdd}|dk(r$|jdd }|jd d }|S) aEscape text to proper XML form, per section 2.3 in the XML specification. @type text: C{str} @param text: Text to escape @type isattrib: C{bool} @param isattrib: Triggers escaping of characters necessary for use as attribute values &&r5<r8>r r6'""replace)textisattribs rr>r>s` <<W %D <<V $D <<V $D1}||C*||C* Krc|jdd}|jdd}|jdd}|jdd}|jd d }|S) Nr^r5r_r8r`r6rbrar]r\rcres runescapeFromXmlrisW << $D << $D <<# &D <<# &D << %D Krc#FK|D]}|j|s|yw)z Filters items in a list by classN) providedBy)rAintns rgenerateOnlyInterfacerns&  >>! Gs!!c#K|D]<}tj|s|j|k(s)|j|k(s9|>yw)z;Filters Element items in a list with matching name and URI.N)IElementrkrr))rArr)rms rgenerateElementsQNamedrqs<    q !affn#GsAAAAc#nK|D],}tj|s|j|k(s)|.yw)zFFilters Element items in a list with matching name, regardless of URI.N)rprkr)rArrms rgenerateElementsNamedrss2    q !affnGs 555ceZdZdZy)r<z/Marker class for pre-serialized XML in the DOM.NrVrWrXrYrZrrr<r<s9rr<c"eZdZdZdZdZdZy) Namespacez7Convenience object for tracking namespace declarations.c||_yN_urir(s rr!zNamespace.__init__s  rc|j|fSryrzrrms r __getattr__zNamespace.__getattr__ 1~rc|j|fSryrzr}s r __getitem__zNamespace.__getitem__rrN)rVrWrXrYr!r~rrZrrrwrwsArrwceZdZdZedZedZedZedZedZ edZ edZ dd Z dd Z d Zd Zy )rpz Interface to XML element nodes. See L{Element} for a detailed example of its general use. Warning: this Interface is not yet complete! z Element's namespace URI z Element's local name z) Default namespace URI of child elements z" Dictionary of element attributes z List of child nodes z' Reference to element's parent element z Dictionary of local prefixes Ncy)aSerializes object to a (partial) XML document @param prefixes: dictionary that maps namespace URIs to suggested prefix names. @type prefixes: L{dict} @param closeElement: flag that determines whether to include the closing tag of the element in the serialized string. A value of C{0} only generates the element's start tag. A value of C{1} yields a complete serialization. @type closeElement: L{int} @param defaultUri: Initial default namespace URI. This is most useful for partial rendering, where the logical parent element (of which the starttag was already serialized) declares a default namespace that should be inherited. @type defaultUri: L{str} @param prefixesInScope: list of prefixes that are assumed to be declared by ancestors. @type prefixesInScope: L{list} @return: (partial) serialized XML @rtype: L{str} NrZ)rrIr9r s rtoXmlzIElement.toXmlrcy)a< Create an element and add as child. The new element is added to this element as a child, and will have this element as its parent. @param name: element name. This can be either a L{str} object that contains the local name, or a tuple of (uri, local_name) for a fully qualified name. In the former case, the namespace URI is inherited from this element. @type name: L{str} or L{tuple} of (L{str}, L{str}) @param defaultUri: default namespace URI for child elements. If L{None}, this is inherited from this element. @type defaultUri: L{str} @param content: text contained by the new element. @type content: L{str} @return: the created element @rtype: object providing L{IElement} NrZ)rr9contents r addElementzIElement.addElementrrcy)a Adds a node as child of this element. The C{node} will be added to the list of childs of this element, and will have this element set as its parent when C{node} provides L{IElement}. If C{node} is a L{str} and the current last child is character data (L{str}), the text from C{node} is appended to the existing last child. @param node: the child node. @type node: L{str} or object implementing L{IElement} NrZ)nodes raddChildzIElement.addChild'rrcy)aC Adds character data to this element. If the current last child of this element is a string, the text will be appended to that string. Otherwise, the text will be added as a new child. @param text: The character data to be added to this element. @type text: L{str} NrZrhs r addContentzIElement.addContent5rrNr r#NrU)rVrWrXrYrr)rr9rCrEparentr?rrrrrZrrrprpsj 3 4C 1 2DJKJCDJ45H D EFBCM 6 0    rrpceZdZdZdZddZdZdZdZdZ d Z d Z e Z d Z dd Zd ZdZdZdZdedefdZddZdZdZddZddZdZy)ElementaPRepresents an XML element node. An Element contains a series of attributes (name/value pairs), content (character data), and other child Element objects. When building a document with markup (such as HTML or XML), use this object as the starting point. Element objects fully support XML Namespaces. The fully qualified name of the XML Element it represents is stored in the C{uri} and C{name} attributes, where C{uri} holds the namespace URI. There is also a default namespace, for child elements. This is stored in the C{defaultUri} attribute. Note that C{''} means the empty namespace. Serialization of Elements through C{toXml()} will use these attributes for generating proper serialized XML. When both C{uri} and C{defaultUri} are not None in the Element and all of its descendents, serialization proceeds as expected: >>> from twisted.words.xish import domish >>> root = domish.Element(('myns', 'root')) >>> root.addElement('child', content='test') >>> root.toXml() u"test" For partial serialization, needed for streaming XML, a special value for namespace URIs can be used: L{None}. Using L{None} as the value for C{uri} means: this element is in whatever namespace inherited by the closest logical ancestor when the complete XML document has been serialized. The serialized start tag will have a non-prefixed name, and no xmlns declaration will be generated. Similarly, L{None} for C{defaultUri} means: the default namespace for my child elements is inherited from the logical ancestors of this element, when the complete XML document has been serialized. To illustrate, an example from a Jabber stream. Assume the start tag of the root element of the stream has already been serialized, along with several complete child elements, and sent off, looking like this:: ... Now suppose we want to send a complete element represented by an object C{message} created like: >>> message = domish.Element((None, 'message')) >>> message['to'] = 'user@example.com' >>> message.addElement('body', content='Hi!') >>> message.toXml() u"Hi!" As, you can see, this XML snippet has no xmlns declaration. When sent off, it inherits the C{jabber:client} namespace from the root element. Note that this renders the same as using C{''} instead of L{None}: >>> presence = domish.Element(('', 'presence')) >>> presence.toXml() u"" However, if this object has a parent defined, the difference becomes clear: >>> child = message.addElement(('http://example.com/', 'envelope')) >>> child.addChild(presence) >>> message.toXml() u"Hi!" As, you can see, the element is now in the empty namespace, not in the default namespace of the parent or the streams'. @type uri: L{str} or None @ivar uri: URI of this Element's name @type name: L{str} @ivar name: Name of this Element @type defaultUri: L{str} or None @ivar defaultUri: URI this Element exists within @type children: L{list} @ivar children: List of child Elements and content @type parent: L{Element} @ivar parent: Reference to the parent Element, if any. @type attributes: L{dict} @ivar attributes: Dictionary of attributes associated with this Element. @type localPrefixes: L{dict} @ivar localPrefixes: Dictionary of namespace declarations on this element. The key is the prefix to bind the namespace uri to. rNc|xsi|_|\|_|_|8|j|jjvr|j|_n||_|xsi|_g|_d|_y)a @param qname: Tuple of (uri, name) @param defaultUri: The default URI of the element; defaults to the URI specified in C{qname} @param attribs: Dictionary of attributes @param localPrefixes: Dictionary of namespace declarations on this element. The key is the prefix to bind the namespace uri to. N)r?r)rrr9rCrEr)rqnamer9attribsr?s rr!zElement.__init__sj+0b#$)  $(($2D2D2K2K2M"M"hhDO(DO!-R  rc|jD]+}tj|s|j|k(s)|cS|j dr t |y)N_)rErprkr startswithAttributeError)rkeyrms rr~zElement.__getattr__sN A""1%!&&C-  >>#  % %rc>|j|j|SryrC_dqarrs rrzElement.__getitem__styy~..rc<|j|j|=yryrrs r __delitem__zElement.__delitem__s OODIIcN +rc@||j|j|<yryr)rrvalues r __setitem__zElement.__setitem__s*/ #'rcN|jD]}t|ts|cSy)z9 Retrieve the first CData (content) node r#)rEr;r=r}s r __unicode__zElement.__unicode__s+ A!S! rc6t|jdS)zH Retrieve the first character data node as UTF-8 bytes. zutf-8)r=encoder%s r __bytes__zElement.__bytes__s4y((rc:t|tr |ds|dS|S)z$Dequalify an attribute key as neededrr )r;rD)rattrs rrz Element._dqas dE "477NKrc:|jj||S)z.Retrieve the value of attribname, if it exists)rCget)r attribnamedefaults r getAttributezElement.getAttributes"":w77rc<|j||jvS)z+Determine if the specified attribute exists)rrC)rattribs r hasAttributezElement.hasAttributesyy DOO33rc^|jj|j|d|k(S)zbSafely compare the value of an attribute against a provided value. L{None}-safe. N)rCrr)rrrs rcompareAttributezElement.compareAttributes) ""499V#4d;uDDrc@|j}||}||||<|||<y)z!Swap the values of two attribute.N)rC)rleftrightdls rswapAttributeValueszElement.swapAttributeValuess* OO dGE($%rcttj|r||_|jj ||S)zAdd a child to this Element.)rprkrrEr:)rrs rrzElement.addChilds.   t $DK T" rrereturnc&t|ts%td|dt|jd|j }t |dkDrt|dtr |d|z|d<n|j|tt|dS)z#Add some text data to this Element.zExpected str not z ()rr,) r;r= TypeErrortyperVrEr r:r)rrerTs rrzElement.addContents$$/xr$t*:M:M9NaPQ Q MM q6A:*QrUC0bEDLAbE HHTNC2rct|tr||d}t||}n| |j}t||f|}|j ||r|j ||Sr)r;rDrr9rr)rrr9rchilds rrzElement.addElementsi dE "!!!W D*-E!!__ Z. ;E e    W % rcL|jjt|y)z=Add a pre-serialized chunk o' XML as a child of this Element.N)rEr:r<)r rawxmlstrings r addRawXmlzElement.addRawXml#s ]<89rc|dtjz|jd<tjdzt_y)z[Add a unique (across a given Python session) id attribute to this Element. zH_%didr N)r _idCounterrCr%s r addUniqueIdzElement.addUniqueId's0!');); ;$//!3rch|t|jtSt|j||S)a Iterate across all children of this Element that are Elements. Returns a generator over the child elements. If both the C{uri} and C{name} parameters are set, the returned generator will only yield on elements matching the qualified name. @param uri: Optional element URI. @type uri: L{str} @param name: Optional element name. @type name: L{str} @return: Iterator that yields objects implementing L{IElement}. )rnrErprq)rr)rs relementszElement.elements.s- <(A A)$--sC Crcdt||}|j||||jS)z4Serialize this Element and all children to a string.)rr )rIr9)SerializerClassrFr&)rrrIr9r ss rrz Element.toXmlAs, X O D| Kzz|rcX|jD]}tj|s|cSyry)rErprk)rrTs rfirstChildElementzElement.firstChildElementGs- A""1% r)NNNryrUr)rVrWrXrYrr!r~rrrrr__str__rrrrrrr=rrrrrrrrZrrrrBs`DJ( /,0) G84E  s  s  ":4D& rrceZdZdZy) ParserErrorz,Exception thrown when a parsing error occursNrurZrrrrNs6rrct t}|S#t$r t tdt}|cYSwxYw)zPreferred method to construct an ElementStream Uses Expat-based stream if available, and falls back to Sux if necessary. zNo parsers available :()ExpatElementStream ImportErrorSuxElementStream Exception)ess r elementStreamrTsB   !   #56 6   s &77cReZdZdZdZdZdZdZdZdZ dd d d d d Z dZ dZ y)rc|jd|_d|_d|_d|_d|_d|_g|_g|_y)NF) connectionMadeDocumentStartEvent ElementEventDocumentEndEventcurrElemrootElemdocumentStarteddefaultNsStackrr%s rr!zSuxElementStream.__init__dsL "&  $  $ rc |j|y#tj$r}tt |d}~wwxYwry) dataReceivedr ParseErrorrr=rbufferes rparsezSuxElementStream.parseos8 &   f %~~ &c!f% % &sA;Ac|j}tdt|jdzdzdD]}|||vs |||cSy)Nr,r r-r/s rfindUrizSuxElementStream.findUrius\  rC 0 01A5;R@ (Aq!Qx'' (rc6d}i}i}d}t|jD]2\}}|jdst|\} } | |}n||| <||=4|jj ||*t |jdkDr|jd}nd}t|\} }| |}n|j| }|jD]:\}}t|\} } | ||| <t|||j| | f<<t||f|||} |jj ||jr5|j| |_ y|jj| |_ y| |_d|_ |j| y)Nxmlnsrr,r#T)rAr@rrrr:r rrrirrrrrr)rrrCr9r?rr)rOrPxrLr0rmrs r gotTagStartzSuxElementStream.gotTagStart~s  ))+, "DAq||G$#A19!"J'(M!$qM "  .  4&&'!+!004  $D)  >C,,v&C$$& CDAq?DAqy 0?0Ba1,-  C S$KWm D "":.   }}$ ! !% 6 6q 9 DM#'D  # #A &rc|j=t|tr|jd}|jj |yyNasciirr;bytesdecoderrdatas rgotTextzSuxElementStream.gotText; == $$&{{7+ MM $ $T * %rc|j=t|tr|jd}|jj |yyrrrs rgotCDatazSuxElementStream.gotCDatarrcyryrZrs r gotCommentzSuxElementStream.gotComments rr\r5r8r6ra)ampltgtaposquotc|tjvrPtj|}t|tr|j d}|j j |yyr)rentitiesr;rrrr)r entityRefrs rgotEntityReferencez#SuxElementStream.gotEntityReferencesR (11 1#,,Y7D$&{{7+ MM $ $T * 2rc|j tdt|\}}||jd}n|j |}|j U|jj |k7s|jj|k7r td|jd|_y|j j |k7s|j j|k7r td|jj|jj|j j>|j|j _ |j|j d|_y|j j|_y)Nz%Element closed after end of document.r,zMismatched root elementszMalformed element close) rrrrrrrr)rrrGrr)rrr0r)s r gotTagEndzSuxElementStream.gotTagEnds> == EF F$D)  >%%b)C,,v&C == }}!!T)T]]->->#-E!"<==  ! ! # DM }}!!T)T]]->->#-E!";<<    "    # # %}}##+'+}} $!!$--0 $ !% 4 4 rN) rVrWrXr!rrrrrrrrr rZrrrrcsH & ='~+ +   H+*5rrc6eZdZdZdZdZdZdZdZdZ y) rcddl}d|_d|_d|_|j|_|j dd|_|j|j _|j|j _ |j|j _ |j|j _|j|j _d|_dg|_d|_i|_y)NrzUTF-8r7r#)pyexpatrrrerror ParserCreateparser_onStartElementStartElementHandler _onEndElementEndElementHandler_onCdataCharacterDataHandler_onStartNamespaceStartNamespaceDeclHandler_onEndNamespaceEndNamespaceDeclHandlerrrrr?)rr s rr!zExpatElementStream.__init__ s"&  $]] **7C8 *.*>*> '(,(:(: %+/== (040F0F -.2.B.B + !d rc |jj|y#|j$r}tt |d}~wwxYwry)rParser rr=rs rrzExpatElementStream.parses< & KK  f %zz &c!f% % &sAAAcd|jdd}t|dk(rd|f}i}g}|jD]:\}}d|vs |jdd}|||d|df<|j|<|j ||D]}||=t ||j d||j} i|_|jdk(rM|jdk7r6|jjj| |j| _ | |_ yd|_|j| y)Nr7r r#rr,) rsplitr r@r:rrrr?rrrErr) rrattrsrnewAttrstoDeleterOrPaqnamers rrz"ExpatElementStream._onStartElement$s4 C# u:?JEKKM #DAqax#q)34&)VAY/0"  #  X Aa  E4..r2E4;M;M N   1 $}}$ &&--a0==DM$%D  # #A &rc|j|jy|jj#|j|jd|_y|jj|_yry)rrrr)rrs rrz ExpatElementStream._onEndElementJsV ==  ! ! #]] ! ! )   dmm , DM !MM00DMrcZ|jdk7r|jj|yyry)rrrs rrzExpatElementStream._onCdataZs% ==D MM $ $T * !rc^||jj|y||j|<yry)rr:r?)rr0r)s rrz$ExpatElementStream._onStartNamespace^s- >    & &s +),D  v &rc>||jjyyry)rrG)rr0s rrz"ExpatElementStream._onEndNamespacefs >    # # % rN) rVrWrXr!rrrrrrrZrrrr s& $& $'L1 +-&rrN)r)rYtypingrzope.interfacerrr twisted.webrrrrrr>rirnrqrsr=r<rwrprrrr XMLParserrrrZrrr*s <<5e < uup"& C  \ y\ ~ XHHHV ) e5s}}e5P^&^&r