U eJ @sFdZzddlmZWn ek r4ddlmZYnXddlmZddlm Z zddl m Z WnFek rzddl m Z Wn ek rddl m Z YnXYnXe ZddlZeeeeddd krdd lmZdd lmZzeZWnek r eZYnXzeZWnek r.eZYnXd Zd ZdZ Gddde!Z"Gddde#Z$deddddfddZ%d(ddZ&d)ddZ'd*d!d"Z(e)d#krBddl*Z*ddl+Z+ze*j,j-Z,e*j.j-Z.Wn"e/k re*j,Z,e*j.Z.YnXe*j0d$d\Z1ee1Z1d%d&Z2z(e%e,e1e2e d'Z3e1dkr(e2ge3Wne4k r@YnXdS)+z:Makes working with XML feel like you are working with JSON)pyexpat)expat) XMLGenerator)AttributesImpl)StringION)) OrderedDict) isgeneratorz Martin Blechz0.13.0MITc@s eZdZdS)ParsingInterruptedN)__name__ __module__ __qualname__rr7/opt/hc_python/lib/python3.8/site-packages/xmltodict.pyr 'sr c@s~eZdZddddddddd edd d d d fd d ZddZddZddZddZddZ ddZ ddZ ddZ ddZ d S) _DictSAXHandlerrcGsdSNTr)argsrrr.z_DictSAXHandler.T@#textFN:z#commentcCsxg|_g|_g|_d|_||_||_||_||_||_||_ ||_ ||_ | |_ | |_ | |_| |_| |_| |_||_dSN)pathstackdataitem item_depth xml_attribs item_callback attr_prefix cdata_key force_cdatacdata_separator postprocessordict_constructorstrip_whitespacenamespace_separator namespacesnamespace_declarations force_list comment_key)selfr!r#r"r$r%r&r'r(r)r*r+r,r.r/rrr__init__,s&z_DictSAXHandler.__init__cCs|jdkr|S||j}|dkr&|S|d|||dd}}z|j|}Wntk rj|}YnX|st|S|j||fSdS)N)r,rfindr+KeyErrorjoin)r0 full_namei namespacenameZshort_namespacerrr _build_nameOs   z_DictSAXHandler._build_namecCs2t|tr|S|t|ddd|dddS)Nrrr3) isinstancedictr)zip)r0attrsrrr_attrs_to_dict_s z_DictSAXHandler._attrs_to_dictcCs||j|p d<dS)Nr)r-)r0prefixurirrrstartNamespaceDecldsz"_DictSAXHandler.startNamespaceDeclcCs||}||}|r2|jr2|j|d<||_|j||p@dft|j|jkr|j|j |j f|j rg}| D]F\}}|j ||}|jr||j||}n||f}|r|||q|||}nd}|pd|_ g|_ dS)NZxmlns)r;r@r-r)rappendlenr!rr rr"itemsr$r()r0r7r?r:Z attr_entrieskeyvalueentryrrr startElementgs*        z_DictSAXHandler.startElementcCs||}t|j|jkrX|j}|dkr@|js2dn |j|j}||j|}|sXt |j r|jsjdn |j|j}|j}|j \|_|_|j r|r| pd}|r|jr|dkr|}|dk r|r|||j|||j|||_n||j|||_n d|_g|_|j dSr)r;rErr!r rr'r6r#r rpopr*stripr&r) push_datar%)r0r7r:r Zshould_continuerrrr endElements8       z_DictSAXHandler.endElementcCs |js|g|_n |j|dSr)rrDr0rrrr characterss z_DictSAXHandler.characterscCs&|jr|}||j|j||_dSr)r*rLrMr r/rOrrrcommentssz_DictSAXHandler.commentscCs|jdk r.||j||}|dkr&|S|\}}|dkr>|}z.||}t|tr^||n ||g||<Wn4tk r|||r|g||<n|||<YnX|Sr)r(rr)r<listrDr5_should_force_list)r0r rGrresultrHrrrrMs"     z_DictSAXHandler.push_datacCsZ|js dSt|jtr|jSz ||jkWStk rT||jdd||YSXdS)NFr2)r.r<bool TypeErrorr)r0rGrHrrrrSs  z"_DictSAXHandler._should_force_list)rrr_dictr1r;r@rCrJrNrPrQrMrSrrrrr+s0 #rFrTc Ks.tfd|i|}t|tr.|s$d}||}|s6d}|||} z d| _Wntk r`YnX|j| _|j | _ |j | _ |j | _|r|j| _d| _|rzd} | j| dWn(tk rdd| _dd| _YnXt|d r| |n:t|r|D]} | | d q| d dn | |d|jS) aParse 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(""" ... ... 1 ... 2 ... ... """) >>> 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(""" ... ... 1 ... 2 ... """, 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('12x', ... 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('hello', 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: host1 Linux em0 10.0.0.1 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: 1 2 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+utf-8NTz4http://apache.org/xml/features/disallow-doctype-declcSsdSrrxrrrrprzparse..cWsdS)Nr3rrYrrrrrrreadFr)rr<_unicodeencode ParserCreateordered_attributesAttributeErrorrCStartNamespaceDeclHandlerrJStartElementHandlerrNEndElementHandlerrPCharacterDataHandlerrQCommentHandler buffer_text_readerZ setFeatureDefaultHandlerExternalEntityRefHandlerhasattr ParseFiler Parser ) Z xml_inputencodingrZprocess_namespacesr+Zdisable_entitiesZprocess_commentskwargshandlerparserfeaturechunkrrrparsesP         rsrcCsl|s|Sz||d\}}Wntk r0Yn8X|||}|rdd||rX|nd|||n|}|S)Nr3z{}{}{}{}r)rsplit ValueErrorgetrLformat startswith)r:r,Zns_sepr$nsZns_resrrr_process_namespace~s"rzr  cCst|| | |}|dk r4|||}|dkr,dS|\}}t|drRt|tsRt|trX|g}t|D]@\}}| r|dkr|dkrtd|dkrt}n\t|tr|rt d}qt d}n:t|ts| rt|drt|tst| |ff}nt |}t|tr t||ff}d}t}g}| D]\}}||kr<|}q"| |rt|| | |}|dkrt|tr| D]0\}}d |rd |nd }t |||<qtq"t|t st |}|||t |d<q"|||fq"|r||| ||t||r"|r"|||D]0\}}t||||||d |||| | | | d q&|dk rl|||r|r||| |||r`|r`||q`dS) N__iter__rzdocument with multiple rootstruefalsez@xmlnszxmlns{}z:{}rr3)r,r+ expand_iter)rzrjr< _basestringr= enumeraterurWrUr\rFrxrwrErDZignorableWhitespacerJr_emitrPrN)rGrHcontent_handlerr$r%depth preprocessorprettyZnewlindentr+r, full_documentrrTindexvcdatar?childrenikZivkattrZ child_keyZ child_valuerrrrs                   rrXc Ks|rt|dkrtdd}|dkr.t}d}|r@t||d}n t||}|rV||D] \}} t|| |fd|i|q^|r||r|} z| |} Wnt k rYnX| SdS)axEmit 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. r3z$Document must have exactly one root.FNTr) rErurrZ startDocumentrFrZ endDocumentgetvaluedecoder`) Z input_dictoutputrmrZshort_empty_elementsrnZ must_returnrrGrHrrrunparses0 r__main__r3cCst||ftdSr)marshaldumpstdout)rr rrr handle_itemsr)r!r#r))rr) rrrNFr{r|rNTN)NrXTF)5__doc__Z defusedexpatrr ImportError xml.parsersZxml.sax.saxutilsrZxml.sax.xmlreaderr cStringIOrior=rWplatformtuplemapintpython_version_tuple collectionsr inspectr basestringr NameErrorstrunicoder\ __author__ __version__ __license__ Exceptionr objectrrsrzrrrsysrstdinbufferrr`argvr!rrootKeyboardInterruptrrrrs        5  O +