
    gwbJ                        d Z 	 ddlmZ n# e$ r	 ddlmZ Y nw xY wddlmZ ddlm	Z	 	 ddl
mZ n$# e$ r 	 ddlmZ n# e$ r	 ddlmZ Y nw xY wY nw xY weZddlZ e ee ej                    dd                             d	k     rdd
lmZ ddlmZ 	 eZn# e$ r eZY nw xY w	 eZn# e$ r eZY nw xY wdZdZdZ  G d de!          Z" G d de#          Z$deddddfdZ%d#dZ&	 	 	 	 	 	 	 	 	 	 	 d$dZ'	 	 d%dZ(e)dk    rddl*Z*ddl+Z+	 e*j,        j-        Z,e*j.        j-        Z.n# e/$ r e*j,        Z,e*j.        Z.Y nw xY we*j0        d d         \  Z1 ee1          Z1d! Z2	  e%e,e1e2e"          Z3e1dk    r e2g e3           dS dS # e4$ r Y dS w xY w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                       e Zd ZdS )ParsingInterruptedN)__name__
__module____qualname__     +/usr/lib/python3/dist-packages/xmltodict.pyr   r   '   s        Dr   r   c                   j    e Zd Zdd ddddddedd	ddd
fdZd Zd Zd Zd Zd Z	d Z
d Zd Zd ZdS )_DictSAXHandlerr   c                      dS NTr   )argss    r   <lambda>z_DictSAXHandler.<lambda>.   s    T r   T@#textF N:z#commentc                     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/   r0   r1   r3   r4   s                  r   __init__z_DictSAXHandler.__init__,   s     	
		$&*&"&.* 0 0#6 $&6&6&8&8#$&r   c                    | j         |S |                    | j                  }|dk    r|S |d |         ||dz   d          }}	 | j         |         }n# t          $ r |}Y nw xY w|s|S | j                            ||f          S )N   )r1   rfindr0   KeyErrorjoin)r5   	full_namei	namespacenameshort_namespaces         r   _build_namez_DictSAXHandler._build_nameO   s    ?"OOD45577#BQB-1Q3444		("oi8OO 	( 	( 	('OOO	( 	JK+00/41HIIIs   A A! A!c           	          t          |t                    r|S |                     t          |dd d         |dd d                             S )Nr   r   r9   )
isinstancedictr.   zip)r5   attrss     r   _attrs_to_dictz_DictSAXHandler._attrs_to_dict_   sK    eT"" 	L$$Sqt!teADqDk%B%BCCCr   c                     || j         |pd<   d S )Nr   )r2   )r5   prefixuris      r   startNamespaceDeclz"_DictSAXHandler.startNamespaceDecld   s    47#FLb111r   c                    |                      |          }|                     |          }|r*| j        r#| j        |d<   |                                 | _        | j                            ||pd f           t          | j                  | j        k    r| j                            | j	        | j
        f           | j        rg }|                                D ]a\  }}| j        |                      |          z   }| j        r|                     | j        ||          }n||f}|r|                    |           b|                     |          }nd }|pd | _	        g | _
        d S d S )Nxmlns)rB   rH   r2   r.   r"   appendlenr&   r#   r%   r$   r'   itemsr)   r-   )r5   r=   rG   r@   attr_entrieskeyvalueentrys           r   startElementz_DictSAXHandler.startElementg   sy   	**##E** 	BT0 	B!8E'N*.*?*?*A*AD'	$.///ty>>DO++Jty$)4555 !"'++-- 3 3JC*4+;+;C+@+@@C) - $ 2 249c5 I I!$e 3$++E222--l;;DIDIII! ,+r   c                 l   |                      |          }t          | j                  | j        k    r\| j        }|(| j        sd n| j                            | j                  }|                     | j        |          }|st                      | j
        r| j        sd n| j                            | j                  }| j        }| j
                                        \  | _        | _        | j        r|r|                                pd }|r| j        r||                                 }|@|r|                     || j        |           |                     | j        ||          | _        n0|                     | j        ||          | _        nd | _        g | _        | j                                         d S r!   )rB   rP   r"   r&   r%   r$   r,   r<   r(   r   r#   popr/   stripr+   r.   	push_datar*   )r5   r=   r@   r%   should_continuer$   s         r   
endElementz_DictSAXHandler.endElement   s   	**ty>>T_,,9D|$(I B!166tyAA  #00DAAO" +(***: 	 $	 >DD-2249== 9D#':>>#3#3 DIty$ , ,zz||+t /( /T\,,.. ?NN4>>> NN49dDAA		 NN49dDAA		DIDI	r   c                 \    | j         s
|g| _         d S | j                             |           d S r!   )r$   rO   r5   r$   s     r   
charactersz_DictSAXHandler.characters   s5    y 	#DIIIIT"""""r   c                     | j         r|                                }|                     | j        | j        |          | _        d S r!   )r/   rY   rZ   r%   r4   r^   s     r   commentsz_DictSAXHandler.comments   s:      	 ::<<DNN49d.>EE			r   c                 f   | j         %|                      | j        ||          }||S |\  }}||                                 }	 ||         }t          |t                    r|                    |           n||g||<   n2# t          $ r% |                     ||          r|g||<   n|||<   Y nw xY w|S r!   )r-   r"   r.   rD   listrO   r;   _should_force_list)r5   r%   rS   r$   resultrT   s         r   rZ   z_DictSAXHandler.push_data   s    )''	3==F~IC<((**D
	!IE%&& *T"""""DMS	 	! 	! 	!&&sD11 !!FS		 S			!
 s   :A? ?,B.-B.c                     | j         sdS t          | j         t                    r| j         S 	 || j         v S # t          $ r' |                      | j        d d         ||          cY S w xY w)NFr8   )r3   rD   bool	TypeErrorr"   )r5   rS   rT   s      r   rd   z"_DictSAXHandler._should_force_list   s     	5dot,, 	#?"	?$/)) 	? 	? 	???49SbS>3>>>>>	?s   5 .A&%A&)r   r   r   _dictr6   rB   rH   rL   rV   r\   r_   ra   rZ   rd   r   r   r   r   r   +   s        11! ""!##"'"&%(  '!' !' !' !'FJ J J D D D
8 8 8  2  ># # #F F F
  *? ? ? ? ?r   r   Fr   Tc                    t          dd|i|}t          | t                    r|sd}|                     |          } |sd} |j        ||          }		 d|	_        n# t          $ r Y nw xY w|j        |	_        |j	        |	_
        |j        |	_        |j        |	_        |r|j        |	_        d|	_        |r?	 d}
|	j                            |
d           n # t          $ r d |	_        d |	_        Y nw xY wt-          | d          r|	                    |            nWt1          |           r2| D ]}|	                    |d	           |	                    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',
                },
            }
    r0   utf-8NTz4http://apache.org/xml/features/disallow-doctype-declc                     d S r!   r   xs    r   r   zparse.<locals>.<lambda>p  s    d r   c                      dS )Nr9   r   rm   s    r   r   zparse.<locals>.<lambda>r  s     r   readFr   r   )r   rD   _unicodeencodeParserCreateordered_attributesAttributeErrorrL   StartNamespaceDeclHandlerrV   StartElementHandlerr\   EndElementHandlerr_   CharacterDataHandlerra   CommentHandlerbuffer_text_reader
setFeatureDefaultHandlerExternalEntityRefHandlerhasattr	ParseFiler   Parser%   )	xml_inputencodingr   process_namespacesr0   disable_entitiesprocess_commentskwargshandlerparserfeaturechunks               r   parser      s   L  ( (2E ( &( (G)X&& / 	H$$X..	 #"U F$(!!    (/'AF$!(!5F&1F")"4F 1 ' 0F 
;		;LGN%%gt4444 	; 	; 	; %3NF!.:lF+++	; y&!! &####	Y		 & 	& 	&ELLu%%%%SY%%%<s$   A 
A('A(3C C.-C.r   c                    |s| S 	 |                      |d          \  }} |                    |                    |                    }|r/d                    |                    |          r|nd|||           n| } n# t
          $ r Y nw xY w| S )Nr9   z{}{}{}{}r   )rsplitgetrY   format
startswith
ValueError)r@   r1   ns_sepr)   nsns_ress         r   _process_namespacer   ~  s     6;;vq))D  5 566 &,6z  ==55=KK2FD" " "15 		     Ks   A; ;
BBr   
	c                    t          | ||
|          } | || |          }|d S |\  } }t          |d          r*t          |t                    st          |t                    r|g}t          |          D ]\  }}|r|dk    r|dk    rt          d          |t                      }nt          |t                    r"|rt          d          }nnt          d          }n^t          |t                    sI|r8t          |d          r(t          |t                    st          ||ff          }nt          |          }t          |t                    rt          ||ff          }d }t                      }g }|
                                D ] \  }}||k    r|}|                    |          rt          |||
|          }|dk    rnt          |t                    rY|
                                D ]C\  }}d                    |rd                    |          nd	          }t          |          ||<   Dt          |t                    st          |          }|||t          |          d          <   |                    ||f           |r|                    ||	z             |                    | t#          |                     |r|r|                    |           |D ]$\  }}t%          ||||||d
z   ||||	||
|           %||                    |           |r|r|                    ||	z             |                    |            |r|r|                    |           d S )N__iter__r   zdocument with multiple rootstruefalsez@xmlnszxmlns{}z:{}r   r9   )r1   r0   expand_iter)r   r   rD   _basestringrE   	enumerater   ri   rg   rq   rQ   r   r   rP   rO   ignorableWhitespacerV   r   _emitr_   r\   )rS   rT   content_handlerr)   r*   depthpreprocessorprettynewlindentr0   r1   full_documentr   re   indexvcdatarG   childrenikivkattr	child_keychild_values                             r   r   r     s    S*.A;
O
OCc5))>F
UE:&& %--%&& e$$ 66 66q 	=UaZZEAII;<<<9AA4   		  &V$$W%%At$$ 	   wq*55  jK>X>X  K+-..QKKa%% 	)	1~'((Aggii 	& 	&FBY}}[)) 'J8K(35 5>>jT&:&:> "

 2 21(//10LQ"MM&.qkkd!"h// &!"B/1b[))**+,OORH%%%% 	@//???$$S.*?*?@@@ 	6h 	6//555&. 	+ 	+"I{)[/y%'<$:&9)	+ + + + +
 &&u--- 	@h 	@//???""3''' 	6e 	6//555m66 66r   rk   c                    |r"t          |           dk    rt          d          d}|t                      }d}|rt          ||d          }nt          ||          }|r|                                 |                                 D ]\  }}	t          ||	|fd|i| |r|                                 |r=|                                }		 |		                    |          }	n# t          $ r Y nw xY w|	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.

    r9   z$Document must have exactly one root.FNTr   )rP   r   r   r   startDocumentrQ   r   endDocumentgetvaluedecoderu   )

input_dictoutputr   r   short_empty_elementsr   must_returnr   rS   rT   s
             r   unparser     sP   "  AZA--?@@@K~ 9&vx>>&vx88 (%%''' &&((  
Uc5/ 	 	 		 	 	 	 &##%%% !!	LL**EE 	 	 	D	 s   C! !
C.-C.__main__r9   c                 >    t          j        | |ft                     dS r   )marshaldumpstdout)r"   r%   s     r   handle_itemr     s    dD\6***tr   )r&   r(   r.   )r   r   )r   r   r   NFr   r   r   NTN)Nrk   TF)5__doc__defusedexpatr   r   ImportErrorxml.parsersxml.sax.saxutilsr   xml.sax.xmlreaderr   	cStringIOr   iorE   ri   platformtuplemapintpython_version_tuplecollectionsr   inspectr   
basestringr   	NameErrorstrunicoderq   
__author____version____license__	Exceptionr   objectr   r   r   r   r   r   sysr   stdinbufferr   ru   argvr&   r   rootKeyboardInterruptr   r   r   <module>r      s   < <"------- " " "!!!!!!!!" ) ) ) ) ) ) , , , , , , """""""       %%%%%%%         	 5S/(/11"1"5	6	677&@@000000      KK   KKKHH   HHH 
	 	 	 	 	 	 	 	\? \? \? \? \?f \? \? \?~ #%E!D5q q q qh     !L6 L6 L6 L6^ FJ!&( ( ( (V zJJJNNN	 "   	 HQRRLMZZJ  uU *#.&*, , , ??KD!!!!! ?   1 s    0 A=AAA
AAAB B"!B"&B) )B32B3
D# #D98D9!F F
	F
