
    mhW                        d Z ddlmZ ddlmZmZ ddlmZ ddlm	Z	 ddl
mZ  G d de          Z G d	 d
          ZdeddddfdZd Zd Zd Zd"dZ	 	 	 	 	 	 	 	 	 	 	 	 d#dZ G d de          Z	 	 d$dZedk    rqddlZddlZej        j        Zej        j        Zej        dd         \  Z ee          Zd  Z 	  eeee e!!          Z"edk    r e g e"           dS dS # e#$ r Y dS w xY wdS )%z:Makes working with XML feel like you are working with JSON    )expat)XMLGeneratorescape)AttributesImpl)StringIO)isgeneratorc                       e Zd ZdS )ParsingInterruptedN)__name__
__module____qualname__     4/usr/local/lib/python3.11/site-packages/xmltodict.pyr
   r
   
   s        Dr   r
   c                   p    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 ZdS )_DictSAXHandlerr   c                      dS NTr   )argss    r   <lambda>z_DictSAXHandler.<lambda>   s    D r   T@#textF N:#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+   r,   r-   r/   r0   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   )r-   rfindr,   KeyErrorjoin)r1   	full_namei	namespacenameshort_namespaces         r   _build_namez_DictSAXHandler._build_name4   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      r5   )
isinstancedictr*   zip)r1   attrss     r   _attrs_to_dictz_DictSAXHandler._attrs_to_dictD   sK    eT"" 	L$$Sqt!teADqDk%B%BCCCr   c                     || j         |pd<   d S )Nr   )r.   )r1   prefixuris      r   startNamespaceDeclz"_DictSAXHandler.startNamespaceDeclI   s    47#FLb111r   c                    |                      |          }|                     |          }| j        r9|s|                                 }| 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)r>   rE   r.   r*   r   appendlenr"   r   r!   r    r#   itemsr%   r)   )r1   r9   rD   r<   attr_entrieskeyvalueentrys           r   startElementz_DictSAXHandler.startElementL   s   	**##E**& 	B 0--//!8E'N*.*?*?*A*AD'	$.///ty>>T_,,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                 ,   |                      |          }t          | j                  | j        k    r| j        }|(| j        sd n| j                            | j                  }|                     | j        |          }|st          | j
        r'| j
                                        \  | _        | _        nd | _        g | _        | j                                         d S | j
        r| j        sd n| j                            | j                  }| j        }| j
                                        \  | _        | _        | j        r|r|                                pd }|r,|                     ||          r||                                 }|@|r|                     || j        |           |                     | j        ||          | _        n0|                     | j        ||          | _        nd | _        g | _        | j                                         d S r   )r>   rM   r   r"   r!   r    r(   r8   r$   r
   r   popr+   strip_should_force_cdatar*   	push_datar&   )r1   r9   r<   r!   should_continuer    s         r   
endElementz_DictSAXHandler.endElementg   s   	** ty>>T_,,9D|$(I B!166tyAA  #00DAAO" )(( z '+z~~'7'7$	499 		IMMOOOF: 	 $	 >DD-2249== 9D#':>>#3#3 DIty$ , ,zz||+t /00t<< /,,.. ?NN4>>> NN49dDAA		 NN49dDAA		DIDI	r   c                 \    | j         s
|g| _         d S | j                             |           d S r   )r    rL   r1   r    s     r   
charactersz_DictSAXHandler.characters   s5    y 	#DIIIIT"""""r   c                     | j         r|                                }|                     | j        | j        |          | _        d S r   )r+   rV   rX   r!   r0   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*   rA   listrL   r7   _should_force_list)r1   r!   rP   r    resultrQ   s         r   rX   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NFr4   )r/   rA   bool	TypeErrorr   r1   rP   rQ   s      r   rb   z"_DictSAXHandler._should_force_list   s     	5dot,, 	#?"	?$/)) 	? 	? 	???49SbS>3>>>>>	?   5 .A&%A&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re   )r'   rA   rf   rg   r   rh   s      r   rW   z#_DictSAXHandler._should_force_cdata   s     	5d&-- 	$##	@$*** 	@ 	@ 	@##DIcrcNC?????	@ri   )r   r   r   rB   r2   r>   rE   rI   rS   rZ   r]   r_   rX   rb   rW   r   r   r   r   r      s         ((#' #' #' #'JJ J J D D D
8 8 8  6) ) )V# # #F F F
  *? ? ?@ @ @ @ @r   r   NFr   Tc                 \   t          d	d|i|}t          | t                    r|pd}|                     |          } |sd} |j        ||          }	d|	_        |j        |	_        |j        |	_	        |j
        |	_        |j        |	_        |r|j        |	_        d|	_        |r
d }
|
|	_        t%          | d          r|	                    |            nWt)          |           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']
        'x'
        >>> doc['a']['b']
        ['1', '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:[('a', {'prop': 'x'}), ('b', None)] item:1
        path:[('a', {'prop': 'x'}), ('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_comments` is `True`, comments will be added using `comment_key`
        (default=`'#comment'`) to the tag that contains the comment.

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

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

                        '#comment': 'c comment',
                        '#text': '1',
                    },
                    'd': '2',
                },
            }
        Comment text is subject to the `strip_whitespace` flag: when it is left
        at the default `True`, comments will have leading and trailing
        whitespace removed. Disable `strip_whitespace` to keep comment
        indentation or padding intact.
    r,   utf-8NTc                       t          d          )Nzentities are disabled)
ValueError)_args_kwargss     r   _forbid_entitieszparse.<locals>._forbid_entitiese  s    4555r   readFr   r   )r   rA   strencodeParserCreateordered_attributesrI   StartNamespaceDeclHandlerrS   StartElementHandlerrZ   EndElementHandlerr]   CharacterDataHandlerr_   CommentHandlerbuffer_textEntityDeclHandlerhasattr	ParseFiler   Parser!   )	xml_inputencodingr   process_namespacesr,   disable_entitiesprocess_commentskwargshandlerparserrq   chunks               r   parser      s   T  ( (2E ( &( (G)S!! /&w$$X..	 #"U F !%F'.'AF$!(!5F&1F")"4F 1 ' 0F 4	6 	6 	6 $4 y&!! &####	Y		 & 	' 	'ELL&&&&S$Y%%%<r   c                     t          | t          t          f          r| S t          | t                    r| rdndS t          |           S )zConvert a value to its string representation for XML output.

    Handles boolean values consistently by converting them to lowercase.
    truefalse)rA   rs   bytesrf   )rQ   s    r   _convert_value_to_stringr   t  sL    
 %#u&& % ,+vvG+u::r   c                    t          | t                    st          | d          |                     d          s|                     d          rt          d| d          d| v sd| v rt          d| d          d	| v rt          d| d
          d| v sd| v rt          d| d          d| v rt          d| d          t	          d | D                       rt          d| d          dS )zValidate an element/attribute name for XML safety.

    Raises ValueError with a specific reason when invalid.

    kind: 'element' or 'attribute' (used in error messages)
    z name must be a string?!zInvalid z# name: cannot start with "?" or "!"<>z name: "<" or ">" not allowed/z name: "/" not allowed"'z name: quotes not allowed=z name: "=" not allowedc              3   >   K   | ]}|                                 V  d S r   )isspace).0chs     r   	<genexpr>z!_validate_name.<locals>.<genexpr>  s*      
(
(B2::<<
(
(
(
(
(
(r   z name: whitespace not allowedN)rA   rs   rn   
startswithany)rQ   kinds     r   _validate_namer   ~  sV    eS!! :D888999 O 0 0 5 5 OMDMMMNNN
e||se||GDGGGHHH
e||@D@@@AAA
e||se||CDCCCDDD
e||@D@@@AAA

(
(%
(
(
((( IGDGGGHHHI Ir   c                 X   t          | t                    r9	 |                     d          } n"# t          $ r}t	          d          |d }~ww xY wt          | t
                    st	          d          d| v rt	          d          |                     d          rt	          d          | S )Nrl   z Comment text must be valid UTF-8zComment text must be a stringz--z Comment text cannot contain '--'-z Comment text cannot end with '-')rA   r   decodeUnicodeDecodeErrorrn   rs   endswith)rQ   excs     r   _validate_commentr     s    % J	JLL))EE! 	J 	J 	J?@@cI	JeS!! :8999u}};<<<~~c =;<<<Ls   - 
AAAr   c                 H   t          | t                    s| S |s| S 	 |                     |d          \  }} |                    |                    |                    }|r/d                    |                    |          r|nd|||           n| } n# t          $ r Y nw xY w| S )Nr5   z{}{}{}{}r   )rA   rs   rsplitgetrV   formatr   rn   )r<   r-   ns_sepr%   nsns_ress         r   _process_namespacer     s    dC    6;;vq))D  5 566 &,6z  ==55=KK2FD" " "15 		     Ks   B 
BBr   
	r   c                 &   t          | t                    r| |k    rt          |t                    r|n|g}t          |	t                    rd|	z  }	|D ]]}|t	          |          }|s|r|                    ||	z             |                    |           |r|                    |           ^d S t          | ||
|          } | || |          }|d S |\  } }t          | d           t          |d          rt          |t          t          f          r|g}t          |          D ]\  }}|r|dk    r|dk    rt          d          |i }nBt          |t          t          f          s&|rt          |d          r||i}nt	          |          }t          |t                    r||i}d }i }g }|                                D ]N\  }}||k    rt	          |          }t          |t                    r|                    |          rt          |||
|          }|dk    rnt          |t                    rY|                                D ]C\  }}t          |d           d                    |rd	| nd
          }t          |          ||<   Dt          |t                    st          |          }|t!          |          d          }t          |d           |||<   t          |t                    r|s7|                    ||f           Pt          |	t                    rd|	z  }	|r|                    ||	z             |                    | t'          |                     |r|r|                    |           |D ]%\  }}t)          ||||||dz   ||||	||
||           &||                    |           |r|r|                    ||	z             |                    |            |r|r|                    |           d S )N element__iter__r   zdocument with multiple rootsz@xmlns	attributezxmlns{}r   r   r5   )r-   r,   expand_iterr0   )rA   rs   ra   intr   ignorableWhitespacecommentr   r   r~   rB   	enumeratern   rN   r   r   rM   rL   rS   r   _emitr]   rZ   )rP   rQ   content_handlerr%   r&   depthpreprocessorprettynewlindentr,   r-   full_documentr   r0   comments_listcomment_textrc   indexvcdatarD   childrenikivkattr	attr_name	child_keychild_values                                 r   r   r     s    #s { 2 2!+E4!8!8Eugfc"" 	"6\F) 
	: 
	:L#3LAAL  D33EFNCCC##L111 :33D999
S*.A;
O
OCc5))>F
U3	"""5*%% EC;)G)G e$$ 86 86q 	=UaZZEAII;<<<9AAAc{++ 	0 0wq*55 0 !$,Q//a 	AAggii 	& 	&FBY044"c"" r}}['A'A 'J8K(35 5>>jT&:&:> "

 - -1&q+666(//10DA"EE&)!ffd!"c** !RBs;//112	y+666#%i "d## B OORH%%%%fc"" 	"6\F 	@//???$$S.*?*?@@@ 	6h 	6//555&. 	D 	D"I{)[/y%'<$:&9){	D D D D D
 &&u--- 	@h 	@//???""3''' 	6e 	6//555q86 86r   c                       e Zd Zd ZdS )_XMLGeneratorc                 p    t          |          }|                     dt          |           d           d S )Nz<!--z-->)r   _writer   )r1   texts     r   r   z_XMLGenerator.comment  s9     &&,6$<<,,,-----r   N)r   r   r   r   r   r   r   r   r     s#        . . . . .r   r   rl   c                    d}|t                      }d}|rt          ||d          }nt          ||          }|r|                                 d}	|                                 D ]8\  }
}|
|k    r|r|	rt	          d          t          |
||f||d| |
|k    rd}	9|r|	st	          d          |r|                                 |r=|                                }	 |                    |          }n# t          $ r Y nw xY w|S dS )aF  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.

    Empty lists are omitted entirely: ``{"a": []}`` produces no ``<a>`` element.
    Provide a placeholder entry (for example ``{"a": [""]}``) when an explicit
    empty container element must be emitted.

    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.

    FNTz$Document must have exactly one root.)r   r0   )
r   r   startDocumentrN   rn   r   endDocumentgetvaluer   AttributeError)
input_dictoutputr   r   short_empty_elementsr0   r   must_returnr   	seen_rootrP   rQ   s               r   unparser     st   * K~ :'$??'99 (%%'''I &&((  
U+-ICDDDc5/jT_jjcijjj+I AY A?@@@ &##%%% !!	LL**EE 	 	 	D	 s   C4 4
D D__main__r5   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   NTNr   )Nrl   TFr   )$__doc__xml.parsersr   xml.sax.saxutilsr   r   xml.sax.xmlreaderr   ior   inspectr   	Exceptionr
   r   r   r   r   r   r   r   r   r   r   r   sysstdinbufferr   argvr"   r   r   rB   rootKeyboardInterruptr   r   r   <module>r      s   < <       1 1 1 1 1 1 1 1 , , , , , ,            	 	 	 	 	 	 	 	v@ v@ v@ v@ v@ v@ v@ v@r #%E!D5j j j jZ	 	 	I I I.     $ ! `6 `6 `6 `6F. . . . .L . . . FJ4>0 0 0 0f zNNNJJJIEZFHQRRLMZZJ  uU *#.&*, , , ??KD!!!!! ?   + s   ?!C$ $C-,C-