
    g0H                     b   d Z ddlmZ ddlmZ ddlmZ ddlmZ 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 dZdZdZ G d de      Z G d d      ZdeddddfdZddZ	 	 	 	 	 	 	 	 	 	 	 ddZ	 	 ddZedk(  rnddlZddl Z 	 ejB                  jD                  Z!ejF                  jD                  Z#ejJ                  dd \  Z& ee&      Z&d Z'	  ee!e&e'e	      Z(e&dk(  r
 e'g e(       yyy# e$$ r ejB                  Z!ejF                  Z#Y Yw xY w# e)$ r Y yw xY w) z:Makes working with XML feel like you are working with JSON    )expat)XMLGenerator)AttributesImpl)StringION   )      )OrderedDict)isgeneratorzMartin Blechz0.14.2MITc                       e Zd Zy)ParsingInterruptedN)__name__
__module____qualname__     /opt/Tautulli/lib/xmltodict.pyr   r      s    r   r   c                   h    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y)_DictSAXHandlerr   c                       yNTr   )argss    r   <lambda>z_DictSAXHandler.<lambda>       r   T@#textF N:z#commentc                    g | _         g | _        g | _        d | _        || _        || _        || _        || _        || _        || _	        || _
        || _        |	| _        |
| _        || _        || _         |	       | _        || _        || _        y 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&8#$&r   c                     | j                   |S |j                  | j                        }|dk(  r|S |d | ||dz   d  }}	 | j                   |   }|s|S | j                  j	                  ||f      S # t        $ r |}Y .w xY w)N   )r1   rfindr0   KeyErrorjoin)r5   	full_namei	namespacenameshort_namespaces         r   _build_namez_DictSAXHandler._build_name=   s    ??"OOD4457#BQ-1Q344		("ooi8O K++00/41HII  	('O	(s   A/ /A=<A=c           	      t    t        |t              r|S | j                  t        |dd d   |dd d               S )Nr   r   r9   )
isinstancedictr.   zip)r5   attrss     r   _attrs_to_dictz_DictSAXHandler._attrs_to_dictM   s=    eT"L$$Sqt!teADqDk%BCCr   c                 *    || j                   |xs d<   y )Nr   )r2   )r5   prefixuris      r   startNamespaceDeclz"_DictSAXHandler.startNamespaceDeclR   s    47##FLb1r   c                    | j                  |      }| j                  |      }|r0| j                  r$| j                  |d<   | j                         | _        | j                  j                  ||xs d f       t        | j                        | j                  k\  r| j                  j                  | j                  | j                  f       | j                  rg }|j                         D ]e  \  }}| j                  | j                  |      z   }| j                  r| j                  | j                  ||      }n||f}|sU|j                  |       g | j                  |      }nd }|xs d | _	        g | _
        y y )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.startElementU   sF   	*##E*T00!88E'N*.*?*?*AD'		$./tyy>T__,JJtyy$))45!"'++- 3JC**4+;+;C+@@C)) $ 2 2499c5 I!$e$++E23 --l;DIDI! -r   c                    | j                  |      }t        | j                        | j                  k(  re| j                  }|3| j
                  sd n$| j                  j                  | j
                        }| j                  | j                  |      }|st        | j                  r| j
                  sd n$| j                  j                  | j
                        }| j                  }| j                  j                         \  | _        | _        | j                  r|r|j                         xs d }|r| j                  r|| j                         }|B|r| j!                  || j"                  |       | j!                  | j                  ||      | _        n1| j!                  | j                  ||      | _        nd | _        g | _        | j                  j                          y 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.endElementn   sj   	*tyy>T__,99D|$(II!1166tyyA  #00DAO"((:: $		D--22499= 99D#'::>>#3 DIty$$zz|+t((T\,,.NN4> NN499dDA	 NN499dDA	DIDI		r   c                 d    | j                   s	|g| _         y | j                   j                  |       y r!   )r$   rO   r5   r$   s     r   
charactersz_DictSAXHandler.characters   s$    yyDIIIT"r   c                     | j                   r|j                         }| j                  | j                  | j                  |      | _        y r!   )r/   rY   rZ   r%   r4   r^   s     r   commentsz_DictSAXHandler.comments   s4      ::<DNN499d.>.>E	r   c                 P   | j                   &| j                  | j                  ||      }||S |\  }}|| j                         }	 ||   }t        |t              r|j                  |       |S ||g||<   	 |S # t        $ r$ | j                  ||      r	|g||<   Y |S |||<   Y |S w xY w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!FS	  !S		!s   &A8 .A8 8!B%B%$B%c                     | j                   syt        | j                   t              r| j                   S 	 || j                   v S # t        $ r# | j                  | 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   sd    doot,??"	?$//)) 	???499Sb>3>>	?s   A )A/.A/)r   r   r   _dictr6   rB   rH   rL   rV   r\   r_   ra   rZ   rd   r   r   r   r   r      sb    1! ""!##"'"&%(  '!'FJ D
82>#F
*?r   r   Fr   Tc                    t        dd|i|}t        | t              r|xs d}| j                  |      } |sd} |j                  ||      }		 d|	_        |j                  |	_        |j                  |	_
        |j                  |	_        |j                  |	_        |r|j                  |	_        d|	_        |r	 d}
|	j$                  j'                  |
d       t-        | d      r|	j/                  |        |j4                  S t1        |       r7| D ]  }|	j3                  |d	        |	j3                  d
d       |j4                  S |	j3                  | d       |j4                  S # t        $ r Y w xY w# t        $ r d |	_        d |	_        Y w xY w)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                      y r!   r   xs    r   r   zparse.<locals>.<lambda>]  r   r   c                       y)Nr9   r   rm   s    r   r   zparse.<locals>.<lambda>_  r   r   readFr   r   )r   rD   str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)S!&w$$X.	"UF$(! (/'A'AF$!(!5!5F&11F")"4"4F ' 0 0F		;LGNN%%gt4 y&!# << 
Y	 	'ELL&	'S$ << 	Y%<<;    	; %3F!.:F+	;s$   E 5E, 	E)(E),FFc                     |s| S 	 | j                  |d      \  }} |j                  |j                  |            }|r)dj                  |j	                  |      r|nd|||       } | S | } | S # t
        $ r Y | S w xY w)Nr9   z{}{}{}{}r   )rsplitgetrY   format
startswith
ValueError)r@   r1   ns_sepr)   nsns_ress         r   _process_namespacer   k  s    6;;vq)D  56 &,   ==5K2FD" K 26 	 K   Ks   A* *	A76A7c                 T   t        | ||
|      } | || |      }|y |\  } }t        |d      rt        |t        t        f      r|g}t        |      D ]S  \  }}|r|dk(  r|dkD  rt        d      |t               }nUt        |t              r|rdnd}n>t        |t        t        f      s(|rt        |d      rt        ||ff      }nt        |      }t        |t              rt        ||ff      }d }t               }g }|j                         D ]  \  }}||k(  r|}|j                  |      rt        |||
|      }|dk(  rOt        |t              r?|j                         D ]+  \  }}dj                  |rd| nd	      }t        |      ||<   - t        |t              st        |      }|||t        |      d  <   |j                  ||f        t        |	t              rd
|	z  }	|r|j                  ||	z         |j!                  | t#        |             |r|r|j                  |       |D ]   \  }}t%        ||||||dz   ||||	||
|       " ||j'                  |       |r|r|j                  ||	z         |j)                  |        |s?|sC|j                  |       V y )N__iter__r   zdocument with multiple rootstruefalsez@xmlnszxmlns{}r   r    r9   )r1   r0   expand_iter)r   r   rD   rq   rE   	enumerater   ri   rg   rQ   r   r   rP   rO   int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   z  s    S*.A;
OCc5)>
U5*%EC;)Ge$ 56qUaZEAI;<<9A4 AAc{+wq*5K+-.Fa	1~'(Aggi 	&FBY}}[)'J8K(35>jT&: "
 -1(//1!A3"E&)!fd- !"c*RB/1b[)*+,OORH%!	&" fc"6\F//?$$S.*?@h//5&. 	+"I{)[/y%'<$:&9)	+	+ &&u-h//?""3'e//5k56r   c                    |rt        |       dk7  rt        d      d}|t               }d}|rt        ||d      }nt        ||      }|r|j	                          | j                         D ]  \  }}	t        ||	|fd|i|  |r|j                          |r$|j                         }		 |	j                  |      }	|	S y# t        $ r Y |	S w xY w)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     s    " ZA-?@@K~&vx>&vx8%%' &&( 
Uc5/ 	 		 ##%!	LL*E    		s   'B; ;	CC__main__r9   c                 <    t        j                  | |ft               yr   )marshaldumpstdout)r"   r%   s     r   handle_itemr     s    dD\6*r   )r&   r(   r.   )r   r   )r   r   r   NF
	r   NTN)Nrk   TF)*__doc__xml.parsersr   xml.sax.saxutilsr   xml.sax.xmlreaderr   ior   rE   ri   platformtuplemapr   python_version_tuplecollectionsr
   inspectr   
__author____version____license__	Exceptionr   r   r   r   r   r   r   sysr   stdinbufferr   ru   argvr&   r   rootKeyboardInterruptr   r   r   <module>r      s   <  ) ,  S/(//1"15	67&@0 
	 	\? \?~ #%E!D5pf  !I6X FJ!&(V z		  ""
 HHQRLMZZJU *#.&*, ?D! -   		$  s$   ,D &D& D#"D#&D.-D.