o bs@sdZddlmZddlmZmZmZddlmZddZ ddiZ Gd d d Z e Z d&d d Z d dZddZddZddZGdddeZGdddZGdddeZeeGdddZGdddeZdd ZGd!d"d"ejZGd#d$d$Zd%S)'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)suxcCs(|dd}t|dkr|Sd|dfS)zSInternal method for splitting a prefixed Element name into its respective parts:Nr)splitlen)namentokr;/usr/lib/python3/dist-packages/twisted/words/xish/domish.py _splitPrefixs   rz$http://www.w3.org/XML/1998/namespacexmlc@s<eZdZdZdddZddZddZd d Zdd dZdS)_ListSerializerz=Internal class which serializes an Element tree into a bufferNcCsFg|_i|_|r|j||jttg|pg|_d|_dSNr) writelistprefixesupdate G_PREFIXESvalues prefixStack prefixCounter)selfrprefixesInScoperrr__init__'s   z_ListSerializer.__init__cCs d|jS)N)joinrrrrrgetValue0s z_ListSerializer.getValuecCs0||jvrd|j|j|<|jd|_|j|S)Nzxn%dr)rrrurirrr getPrefix3s   z_ListSerializer.getPrefixcCs<|j}tdt|jdddD] }|||vrdSqdS)NrTFrranger rprefixstackirrr prefixInScope9s  z_ListSerializer.prefixInScoperrc Cs|jj}t|tr||dSt|tr|t|dS|j}|j}|j|}}|j D] \}} ||j | <q-|j t |j |durH|}|durN|}d} ||ksY||j vrc||} || } | sl|d|n!|d| d|| s|d| d|d|j d| d} ||kr||ks| r| s|d ||j D]\}} |d|d| dq|j D]J\} } t| tr| \}}||}||s|d|d|d|j d||d |d|dt| d dq|d | dt| d dq|d kr|d dSt|jd kr?|d |jD] }|j||dq| s3|d|n|d| d|d n|d|j dS)Nz<%s) defaultUrizz)rappend isinstance SerializedXMLstr escapeToXmlr r#r1 localPrefixesitemsrrlistkeysr$r, attributestupler children serializepop)relem closeElementr1writer r#currentDefaultUripur)inScopekvattr_uri attr_name attr_prefixcrrrr>@sl           $  z_ListSerializer.serializeNN)rr) __name__ __module__ __qualname____doc__rr!r$r,r>rrrrr$s  rcCsH|dd}|dd}|dd}|dkr"|dd }|d 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 &&r-<r0>rr.'""replace)textisattribrrrr6s    r6cCs@|dd}|dd}|dd}|dd}|d d }|S) NrTr-rUr0rVr.rXrWrSrRrYr[rrrunescapeFromXmls     r^ccs |D] }||r |VqdS)z Filters items in a list by classN) providedBy)r9intnrrrgenerateOnlyInterfaces  rbccs4|D]}t|r|j|kr|j|kr|VqdS)z;Filters Element items in a list with matching name and URI.N)IElementr_r r#)r9r r#rarrrgenerateElementsQNameds rdccs*|D]}t|r|j|kr|VqdS)zFFilters Element items in a list with matching name, regardless of URI.N)rcr_r )r9r rarrrgenerateElementsNameds rec@eZdZdZdS)r4z/Marker class for pre-serialized XML in the DOM.NrNrOrPrQrrrrr4r4c@s(eZdZdZddZddZddZdS) Namespacez7Convenience object for tracking namespace declarations.cCs ||_dSN_urir"rrrr zNamespace.__init__cC |j|fSrjrkrrarrr __getattr__rmzNamespace.__getattr__cCrnrjrkrorrr __getitem__rmzNamespace.__getitem__N)rNrOrPrQrrprqrrrrris  ric@sleZdZdZedZedZedZedZedZ edZ edZ dd d Z dddZ ddZddZd S)rcz 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 NrrcCdS)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} Nr)rrAr1rrrrtoXmlzIElement.toXmlcCrr)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} Nr)r r1contentrrr addElementrtzIElement.addElementcCrr)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} Nr)noderrraddChild'rtzIElement.addChildcCrr)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} Nrr]rrr addContent5rtzIElement.addContentNrrNrM)rNrOrPrQrr#r r1r;r=parentr7rsrvrxryrrrrrcs   rcc@seZdZdZdZd0ddZddZdd Zd d Zd d Z ddZ ddZ e Z ddZ d1ddZddZddZddZddZdedefd d!Zd2d"d#Zd$d%Zd&d'Zd2d(d)Zd3d,d-Zd.d/ZdS)4ElementaPRepresents 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. rNcCsX|pi|_|\|_|_|dur|j|jvr|j|_n||_|p"i|_g|_d|_dS)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)r7r#r rr1r;r=r{)rqnamer1attribsr7rrrrs    zElement.__init__cCs>|jD]}t|r|j|kr|Sq|drt|dS)N_)r=rcr_r startswithAttributeError)rkeyrarrrrps  zElement.__getattr__cCs|j||Srjr;_dqarrrrrrqszElement.__getitem__cCs|j||=dSrjrrrrr __delitem__szElement.__delitem__cCs||j||<dSrjr)rrvaluerrr __setitem__szElement.__setitem__cCs"|jD] }t|tr|SqdS)z9 Retrieve the first CData (content) node r)r=r3r5rorrr __unicode__s  zElement.__unicode__cCst|dS)zH Retrieve the first character data node as UTF-8 bytes. zutf-8)r5encoder rrr __bytes__szElement.__bytes__cCst|tr |ds |dS|S)z$Dequalify an attribute key as neededrr)r3r<)rattrrrrrsz Element._dqacCs|j||S)z.Retrieve the value of attribname, if it exists)r;get)r attribnamedefaultrrr getAttributeszElement.getAttributecCs|||jvS)z+Determine if the specified attribute exists)rr;)rattribrrr hasAttributeszElement.hasAttributecCs|j||d|kS)zbSafely compare the value of an attribute against a provided value. L{None}-safe. N)r;rr)rrrrrrcompareAttributeszElement.compareAttributecCs&|j}||}||||<|||<dS)z!Swap the values of two attribute.N)r;)rleftrightdlrrrswapAttributeValuess  zElement.swapAttributeValuescCs t|r||_|j||S)zAdd a child to this Element.)rcr_r{r=r2)rrwrrrrxs  zElement.addChildr[returncCspt|tstd|dt|jd|j}t|dkr,t|dtr,|d||d<n||tt|dS)z#Add some text data to this Element.zExpected str not z ()rr%) r3r5 TypeErrortyperNr=r r2r)rr[rLrrrrys  zElement.addContentcCs^t|tr|dur |d}t||}n|dur|j}t||f|}|||r-|||Sr)r3r<r|r1rxry)rr r1ruchildrrrrvs    zElement.addElementcCs|jt|dS)z=Add a pre-serialized chunk o' XML as a child of this Element.N)r=r2r4)r rawxmlstringrrr addRawXml#szElement.addRawXmlcCs dtj|jd<tjdt_dS)z[Add a unique (across a given Python session) id attribute to this Element. zH_%didrN)r| _idCounterr;r rrr addUniqueId'szElement.addUniqueIdcCs"|dur 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}. N)rbr=rcrd)rr#r rrrelements.s zElement.elementsrrcCs$t||d}|j|||d|S)z4Serialize this Element and all children to a string.)rr)rAr1)SerializerClassr>r!)rrrAr1rsrrrrsAs z Element.toXmlcCs"|jD] }t|r|SqdSrj)r=rcr_)rrLrrrfirstChildElementGs  zElement.firstChildElement)NNNrjrMrz)rNrOrPrQrrrprqrrrr__str__rrrrrrxr5ryrvrrrrsrrrrrr|Bs0b        r|c@rf) ParserErrorz,Exception thrown when a parsing error occursNrgrrrrrNrhrcCs:zt}|WStytdurtdt}|YSw)zPreferred method to construct an ElementStream Uses Expat-based stream if available, and falls back to Sux if necessary. NzNo parsers available :()ExpatElementStream ImportErrorSuxElementStream Exception)esrrr elementStreamTs rc@sdeZdZddZddZddZddZd d Zd d Zd dZ ddddddZ ddZ ddZ dS)rcCs<|d|_d|_d|_d|_d|_d|_g|_g|_dS)NF) connectionMadeDocumentStartEvent ElementEventDocumentEndEventcurrElemrootElemdocumentStarteddefaultNsStackrr rrrrds zSuxElementStream.__init__c Cs8z||WdStjy}ztt|d}~wwrj) dataReceivedr ParseErrorrr5rbuffererrrparseos  zSuxElementStream.parsecCsF|j}tdt|jdddD]}|||vr |||SqdS)Nr%rr&r(rrrfindUrius  zSuxElementStream.findUricCsXd}i}i}d}t|D]\}}|dr+t|\} } | dur$|}n||| <||=q|j||durEt|jdkrC|jd}nd}t|\} }| durR|}n|| }|D]\}}t|\} } | durn||| <q[t |||| | f<q[t ||f|||} |j||j r|j dur| |_ dS|j | |_ dS| |_d|_ || dS)Nxmlnsrr%rT)r9r8rrrr2r rrr^r|rrrxrr)rr r;r1r7r~r#rGrHxrDr)rarrrr gotTagStart~sF           zSuxElementStream.gotTagStartcC2|jdurt|tr|d}|j|dSdSNasciirr3bytesdecoderyrdatarrrgotText   zSuxElementStream.gotTextcCrrrrrrrgotCDatarzSuxElementStream.gotCDatacCsdSrjrrrrr gotCommentszSuxElementStream.gotCommentrRr-r0r.rW)ampltgtaposquotcCs<|tjvrtj|}t|tr|d}|j|dSdSr)rentitiesr3rrrry)r entityRefrrrrgotEntityReferences    z#SuxElementStream.gotEntityReferencecCs|jdur tdt|\}}|dur|jd}n||}|jdur<|jj|ks/|jj|kr3td|d|_dS|jj|ksH|jj|krLtd|j |j |jj durl|j|j_ | |jd|_dS|jj |_dS)Nz%Element closed after end of document.r%zMismatched root elementszMalformed element close) rrrrrrr r#rrr?r{r)rr r)r#rrr gotTagEnds(            zSuxElementStream.gotTagEndN) rNrOrPrrrrrrrrrrrrrrrcs   ? rc@sDeZdZddZddZddZddZd d Zd d Zd dZ dS)rcCsddl}d|_d|_d|_|j|_|dd|_|j|j_|j |j_ |j |j_ |j |j_|j|j_d|_dg|_d|_i|_dS)NrzUTF-8r/r)pyexpatrrrerror ParserCreateparser_onStartElementStartElementHandler _onEndElementEndElementHandler_onCdataCharacterDataHandler_onStartNamespaceStartNamespaceDeclHandler_onEndNamespaceEndNamespaceDeclHandlerrrrr7)rrrrrr s      zExpatElementStream.__init__c Cs:z |j|WdS|jy}ztt|d}~wwrj)rParserrr5rrrrrs  zExpatElementStream.parsec Cs|dd}t|dkrd|f}i}g}|D]\}}d|vr5|dd}|||d|df<||q|||D]}||=q=t||jd||j} i|_|jdkrk|j dkrf|j j | |j | _ | |_ dSd|_| | dS)Nr/rrrr%) rsplitr r8r2rr|rr7rrr=r{r) rr attrsr}newAttrstoDeleterGrHaqnamerrrrr$s.        z"ExpatElementStream._onStartElementcCsF|jdur |dS|jjdur||jd|_dS|jj|_dSrj)rrr{r)rrrrrrJs     z ExpatElementStream._onEndElementcCs|jdkr |j|dSdSrj)rryrrrrrZs zExpatElementStream._onCdatacCs&|dur |j|dS||j|<dSrj)rr2r7)rr)r#rrrr^sz$ExpatElementStream._onStartNamespacecCs|dur |jdSdSrj)rr?)rr)rrrrfsz"ExpatElementStream._onEndNamespaceN) rNrOrPrrrrrrrrrrrr s& rN)r)rQtypingrzope.interfacerrr twisted.webrrrrrr6r^rbrdrer5r4rircr|rrr XMLParserrrrrrrs2   x   _ )