B
    '6cJ                 @   sF  d Z yddlmZ W n  ek
r4   ddlmZ Y nX ddlmZ ddlm	Z	 yddl
mZ W nF ek
r   yddlmZ W n  ek
r   ddlmZ Y nX Y nX eZddlZeeee dd d	k rdd
lmZ ddlmZ yeZW n ek
r
   eZY nX yeZW n ek
r.   eZY nX dZdZdZ G dd de!Z"G dd de#Z$deddddfddZ%d(ddZ&d)ddZ'd*d!d"Z(e)d#krBddl*Z*ddl+Z+ye*j,j-Z,e*j.j-Z.W n" e/k
r   e*j,Z,e*j.Z.Y nX e*j0d$d \Z1ee1Z1d%d& Z2y(e%e,e1e2ed'Z3e1dkr(e2g e3 W n e4k
r@   Y nX dS )+z:Makes working with XML feel like you are working with JSON    )pyexpat)expat)XMLGenerator)AttributesImpl)StringION   )      )OrderedDict)isgeneratorzMartin Blechz0.13.0MITc               @   s   e Zd ZdS )ParsingInterruptedN)__name__
__module____qualname__ r   r   L/home/ankuromar296_gmail_com/.local/lib/python3.7/site-packages/xmltodict.pyr   '   s   r   c               @   s~   e Zd Zddd dddddd	edd
d	d	dfddZdd Zdd Zdd Zdd Zdd Z	dd Z
dd Zdd Zdd Zd	S ) _DictSAXHandlerr   c              G   s   dS )NTr   )argsr   r   r   <lambda>.       z_DictSAXHandler.<lambda>T@z#textF N:z#commentc             C   sx   g | _ g | _g | _d | _|| _|| _|| _|| _|| _|| _	|| _
|| _|	| _|
| _|| _|| _|	 | _|| _|| _d S )N)pathstackdataitem
item_depthxml_attribsitem_callbackattr_prefix	cdata_keyforce_cdatacdata_separatorpostprocessordict_constructorstrip_whitespacenamespace_separator
namespacesnamespace_declarations
force_listcomment_key)selfr   r    r   r!   r"   r#   r$   r%   r&   r'   r(   r)   r+   r,   r   r   r   __init__,   s&    z_DictSAXHandler.__init__c             C   s   | j d kr|S || j}|dkr&|S |d | ||d d   }}y| j | }W n tk
rj   |}Y nX |st|S | j||fS d S )N   )r)   rfindr(   KeyErrorjoin)r-   	full_namei	namespacenameZshort_namespacer   r   r   _build_nameO   s    

z_DictSAXHandler._build_namec             C   s2   t |tr|S | t|dd d |dd d S )Nr   r   r0   )
isinstancedictr&   zip)r-   attrsr   r   r   _attrs_to_dict_   s    
z_DictSAXHandler._attrs_to_dictc             C   s   || j |pd< d S )Nr   )r*   )r-   prefixurir   r   r   startNamespaceDecld   s    z"_DictSAXHandler.startNamespaceDeclc             C   s   |  |}| |}|r2| jr2| j|d< |  | _| j||p@d f t| j| jkr| j| j	| j
f | jrg }xR| D ]F\}}| j|  | }| jr| | j||}n||f}|r~|| q~W | |}nd }|pd | _	g | _
d S )NZxmlns)r8   r=   r*   r&   r   appendlenr   r   r   r   r   itemsr!   r%   )r-   r4   r<   r7   Zattr_entrieskeyvalueentryr   r   r   startElementg   s*    





z_DictSAXHandler.startElementc             C   s  |  |}t| j| jkrX| j}|d kr@| js2d n| j| j}| | j|}|sXt	 | j
r| jsjd n| j| j}| j}| j
 \| _| _| jr|r| pd }|r| jr|d kr|  }|d k	r|r| || j| | | j||| _n| | j||| _nd | _g | _| j  d S )N)r8   rB   r   r   r   r   r$   r3   r    r   r   popr'   stripr#   r&   	push_datar"   )r-   r4   r7   r   Zshould_continuer   r   r   r   
endElement   s4    



z_DictSAXHandler.endElementc             C   s    | j s|g| _ n| j | d S )N)r   rA   )r-   r   r   r   r   
characters   s    
z_DictSAXHandler.charactersc             C   s&   | j r| }| | j| j|| _d S )N)r'   rI   rJ   r   r,   )r-   r   r   r   r   comments   s    z_DictSAXHandler.commentsc             C   s   | j d k	r.|  | j||}|d kr&|S |\}}|d kr>|  }y.|| }t|tr^|| n||g||< W n4 tk
r   | ||r|g||< n|||< Y nX |S )N)r%   r   r&   r9   listrA   r2   _should_force_list)r-   r   rD   r   resultrE   r   r   r   rJ      s"    

z_DictSAXHandler.push_datac             C   sT   | j s
dS t| j tr| j S y
|| j kS  tk
rN   |  | jd d ||S X d S )NFr/   )r+   r9   bool	TypeErrorr   )r-   rD   rE   r   r   r   rO      s    
z"_DictSAXHandler._should_force_list)r   r   r   _dictr.   r8   r=   r@   rG   rK   rL   rM   rJ   rO   r   r   r   r   r   +   s.   r   Fr   Tc             K   s2  t f d|i|}t| tr.|s$d}| |} |s6d}|||}	y
d|	_W n tk
r`   Y nX |j|	_|j	|	_
|j|	_|j|	_|r|j|	_d|	_|ryd}
|	j|
d W n( tk
r   dd |	_dd |	_Y nX t| d	r|	|  n>t| r x| D ]}|	|d
 qW |	dd n|	| d |jS )a  Parse the given XML input and convert it into a dictionary.

    `xml_input` can either be a `string`, a file-like object, or a generator of strings.

    If `xml_attribs` is `True`, element attributes are put in the dictionary
    among regular child elements, using `@` as a prefix to avoid collisions. If
    set to `False`, they are just ignored.

    Simple example::

        >>> import xmltodict
        >>> doc = xmltodict.parse("""
        ... <a prop="x">
        ...   <b>1</b>
        ...   <b>2</b>
        ... </a>
        ... """)
        >>> doc['a']['@prop']
        u'x'
        >>> doc['a']['b']
        [u'1', u'2']

    If `item_depth` is `0`, the function returns a dictionary for the root
    element (default behavior). Otherwise, it calls `item_callback` every time
    an item at the specified depth is found and returns `None` in the end
    (streaming mode).

    The callback function receives two parameters: the `path` from the document
    root to the item (name-attribs pairs), and the `item` (dict). If the
    callback's return value is false-ish, parsing will be stopped with the
    :class:`ParsingInterrupted` exception.

    Streaming example::

        >>> def handle(path, item):
        ...     print('path:%s item:%s' % (path, item))
        ...     return True
        ...
        >>> xmltodict.parse("""
        ... <a prop="x">
        ...   <b>1</b>
        ...   <b>2</b>
        ... </a>""", item_depth=2, item_callback=handle)
        path:[(u'a', {u'prop': u'x'}), (u'b', None)] item:1
        path:[(u'a', {u'prop': u'x'}), (u'b', None)] item:2

    The optional argument `postprocessor` is a function that takes `path`,
    `key` and `value` as positional arguments and returns a new `(key, value)`
    pair where both `key` and `value` may have changed. Usage example::

        >>> def postprocessor(path, key, value):
        ...     try:
        ...         return key + ':int', int(value)
        ...     except (ValueError, TypeError):
        ...         return key, value
        >>> xmltodict.parse('<a><b>1</b><b>2</b><b>x</b></a>',
        ...                 postprocessor=postprocessor)
        {'a': {'b:int': [1, 2], 'b': 'x'}}

    You can pass an alternate version of `expat` (such as `defusedexpat`) by
    using the `expat` parameter. E.g:

        >>> import defusedexpat
        >>> xmltodict.parse('<a>hello</a>', expat=defusedexpat.pyexpat)
        {'a': 'hello'}

    You can use the force_list argument to force lists to be created even
    when there is only a single child of a given level of hierarchy. The
    force_list argument is a tuple of keys. If the key for a given level
    of hierarchy is in the force_list argument, that level of hierarchy
    will have a list as a child (even if there is only one sub-element).
    The index_keys operation takes precedence over this. This is applied
    after any user-supplied postprocessor has already run.

        For example, given this input:
        <servers>
          <server>
            <name>host1</name>
            <os>Linux</os>
            <interfaces>
              <interface>
                <name>em0</name>
                <ip_address>10.0.0.1</ip_address>
              </interface>
            </interfaces>
          </server>
        </servers>

        If called with force_list=('interface',), it will produce
        this dictionary:
        {'servers':
          {'server':
            {'name': 'host1',
             'os': 'Linux'},
             'interfaces':
              {'interface':
                [ {'name': 'em0', 'ip_address': '10.0.0.1' } ] } } }

        `force_list` can also be a callable that receives `path`, `key` and
        `value`. This is helpful in cases where the logic that decides whether
        a list should be forced is more complex.


        If `process_comment` is `True` then comment will be added with comment_key
        (default=`'#comment'`) to then tag which contains comment

            For example, given this input:
            <a>
              <b>
                <!-- b comment -->
                <c>
                    <!-- c comment -->
                    1
                </c>
                <d>2</d>
              </b>
            </a>

            If called with process_comment=True, it will produce
            this dictionary:
            'a': {
                'b': {
                    '#comment': 'b comment',
                    'c': {

                        '#comment': 'c comment',
                        '#text': '1',
                    },
                    'd': '2',
                },
            }
    r(   zutf-8NTz4http://apache.org/xml/features/disallow-doctype-declc             S   s   d S )Nr   )xr   r   r   r   p  r   zparse.<locals>.<lambda>c              W   s   dS )Nr0   r   )rT   r   r   r   r   r  r   readFr   )r   r9   _unicodeencodeParserCreateZordered_attributesAttributeErrorr@   ZStartNamespaceDeclHandlerrG   StartElementHandlerrK   EndElementHandlerrL   CharacterDataHandlerrM   ZCommentHandlerZbuffer_text_readerZ
setFeatureZDefaultHandlerZExternalEntityRefHandlerhasattr	ParseFiler   Parser   )Z	xml_inputencodingr   Zprocess_namespacesr(   Zdisable_entitiesZprocess_commentskwargshandlerparserfeaturechunkr   r   r   parse   sL     







rg   r   c             C   sl   |s| S y|  |d\}} W n tk
r0   Y n8X |||}|rdd||rX|nd||| n| } | S )Nr0   z{}{}{}{}r   )rsplit
ValueErrorgetrI   format
startswith)r7   r)   Zns_sepr!   nsZns_resr   r   r   _process_namespace~  s    &rn   #text
	c             C   s  t | ||
|} |d k	r4|| |}|d kr,d S |\} }t|drRt|tsRt|trX|g}xZt|D ]L\}}|r|dkr|dkrtd|d krt }n\t|tr|rt	d}qt	d}n:t|ts|rt|drt|tst||ff}nt	|}t|trt||ff}d }t }g }x|
 D ]\}}||krB|}q(||rt |||
|}|dkrt|trx<|
 D ]0\}}d|rd|nd	}t	|||< q|W q(t|t	st	|}|||t|d  < q(|||f q(W |r|||	  || t| |r.|r.|| x8|D ]0\}}t||||||d
 ||||	||
|d q4W |d k	r||| |r|r|||	  ||  |rd|rd|| qdW d S )N__iter__r   zdocument with multiple rootstruefalsez@xmlnszxmlns{}z:{}r   r0   )r)   r(   expand_iter)rn   r^   r9   _basestringr:   	enumerateri   rS   rQ   rV   rC   rl   rk   rB   rA   ZignorableWhitespacerG   r   _emitrL   rK   )rD   rE   content_handlerr!   r"   depthpreprocessorprettyZnewlindentr(   r)   full_documentru   rP   indexvcdatar<   childrenikivkattrZ	child_keyZchild_valuer   r   r   rx     s~    












rx   utf-8c       
      K   s   |rt | dkrtdd}|dkr.t }d}|r@t||d}n
t||}|rV|  x,|  D ] \}}	t||	|fd|i| q`W |r|  |r| }	y|		|}	W n t
k
r   Y nX |	S dS )ax  Emit an XML document for the given `input_dict` (reverse of `parse`).

    The resulting XML document is returned as a string, but if `output` (a
    file-like object) is specified, it is written there instead.

    Dictionary keys prefixed with `attr_prefix` (default=`'@'`) are interpreted
    as XML node attributes, whereas keys equal to `cdata_key`
    (default=`'#text'`) are treated as character data.

    The `pretty` parameter (default=`False`) enables pretty-printing. In this
    mode, lines are terminated with `'
'` and indented with `'	'`, but this
    can be customized with the `newl` and `indent` parameters.

    r0   z$Document must have exactly one root.FNTr~   )rB   ri   r   r   ZstartDocumentrC   rx   ZendDocumentgetvaluedecoderY   )
Z
input_dictoutputra   r~   short_empty_elementsrb   Zmust_returnry   rD   rE   r   r   r   unparse  s.    
r   __main__r0   c             C   s   t | |ft dS )NT)marshaldumpstdout)r   r   r   r   r   handle_item  s    r   )r   r    r&   )r   r   )r   ro   r   NFrp   rq   r   NTN)Nr   TF)5__doc__Zdefusedexpatr   r   ImportErrorZxml.parsersZxml.sax.saxutilsr   Zxml.sax.xmlreaderr   	cStringIOr   ior:   rS   platformtuplemapintpython_version_tuplecollectionsr
   inspectr   
basestringrv   	NameErrorstrunicoderV   
__author____version____license__	Exceptionr   objectr   rg   rn   rx   r   r   sysr   stdinbufferr   rY   argvr   r   rootKeyboardInterruptr   r   r   r   <module>   s   

   4
          
D 
*

