gL idZddlmZddlZddlmZddlmZmZm Z ddl Z ddl m Z ddl mZddlmZmZdd lmZdd lmZdd lmZdd lmZdd lmZddlmZmZmZm Z m!Z!m"Z"m#Z#ddl$m%Z%er.ddl&m'Z'ddl(m)Z)ddl*m+Z+ddl,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5ddl6m7Z7eededdzGddZ8Gdde8Z9Gdde8Z: d*dZ;d+d Z}|jDcic] \}}d|vr|jddn||"c}}@}}}}ttj|Dcgc]}|jD]}|c}}} |Dcgc]*}| Dcic]}|||jvr||ndc},}}}|jr:|Dcgc]/}tt|j|j!1}}|Scc}}wcc}}}wcc}wcc}}wcc}}wcc}}}wcc}}wcc}}}wcc}wcc}}wcc}}wcc}}}wcc}}wcc}wcc}}wcc}w)aA Parse xml nodes. This method will parse the children and attributes of elements in ``xpath``, conditionally for only elements, only attributes or both while optionally renaming node names. Raises ------ ValueError * If only elements and only attributes are specified. Notes ----- Namespace URIs will be removed from return node values. Also, elements with missing children or attributes compared to siblings will have optional keys filled with None values. z4Either element or attributes can be parsed not both.*N})r.r/ ValueErrorr0textisspacetagzipfindallattribitemssplitlistdictfromkeyskeysvalues) r9elemselnmchdictskvdrQs r: _parse_nodesz_XMLFrameParser._parse_nodess, ??tST T ??zz$    "wwrww/@ VVRWW-!# +.djj"**S/*J &B277<   "$EGJJsOTbRVVRWWT9T __NSHJ1BCAA$CEZZ   ii,.GGBGGOOB !4!4g>JL   x 89S x( )>  %T%8%8AQR# 0KE425/s+A.txxI(C::"3#&t~~h'?#L;R$+48IItyy4H'szz|;# *2B$++-#{{3/szz|CRU *.++c*:B; $~~h78$+48IItyy4CH$++-'+{{3'7CH 8 ~(S_LL%C 4/((*64>>;K;W NN,Q/((*64>>;K;WC# 0J B;KL LDMMe"FQVVX"F1"F1"FGHMRSdC!Q!&&(]QqT4CSS ::@EF1T#djj!((*56FEF #GCSGs$&R R!R ?R4R Rct|)a* Validate ``xpath``. This method checks for syntax, evaluation, or empty nodes return. Raises ------ SyntaxError * If xpah is not supported or issues with namespaces. ValueError * If xpah does not return any nodes. r>r?s r:_validate_pathz_XMLFrameParser._validate_paths"$''r<ct|)z Validate names. This method will check if names is a list-like and aligns with length of parse nodes. Raises ------ ValueError * If value is not a list and less then length of nodes. r>r?s r:_validate_namesz_XMLFrameParser._validate_namess"$''r<ct|)z Build tree from path_or_buffer. This method will parse XML object into tree either from string/bytes or file location. r>)r9raw_docs r: _parse_docz_XMLFrameParser._parse_docs"$''r<N)r(.FilePath | ReadBuffer[bytes] | ReadBuffer[str]r,rmr-dict[str, str] | Noner.boolr/rr0Sequence[str] | Noner1DtypeArg | Noner2ConvertersArg | Noner3ParseDatesArg | Noner4 str | Noner55FilePath | ReadBuffer[bytes] | ReadBuffer[str] | Noner6dict[str, list[str]] | Noner8rr&r#returnNonerlist[dict[str, str | None]])rS list[Any]rr)r6rrrrrrr)rrrzElement | etree._Element) ri __module__ __qualname____doc__r;r@r[r|r~rrr<r:r*r*>s Qf/F//* /  /  /$//)/*//J///(/(/ !/B(TlgR(" ( (E ( ! (r<r*c8eZdZdZddZddZd dZ d dZy) _EtreeFrameParserz Internal class to parse XML into DataFrames with the Python standard library XML module: `xml.etree.ElementTree`. c8ddlm}|j td|j0|j |j |_|j}|j|j|j}|S|j|}|S)Nrr6zBTo use stylesheet, you need lxml installed and selected as parser.) xml.etree.ElementTreer6r5rErr(xml_docr~rr[r|r9r6rS xml_dictss r:r@z_EtreeFrameParser.parse_datas3 ?? &T  >> !??4+>+>?DL'')E ~~%   e $  &&y1  r<c6d} |jj|j|j}|Dcgc]}|jdD]}|}}}|Dcic]'}|jj D]\}}|| )}}}}| t ||M|jr|gk(r t ||jr|ik(r t ||gk(r|ik(r t ||Scc}}wcc}}}w#ttf$r tdwxYw)z Notes ----- ``etree`` supports limited ``XPath``. If user attempts a more complex expression syntax error will raise. xpath does not return any nodes or attributes. Be sure to specify in `xpath` the parent nodes of children and attributes to parse. If document uses namespaces denoted with xmlns, be sure to define namespaces and use them in xpath.r-rBzxYou have used an incorrect or unsupported XPath expression for etree library or you used an undeclared namespace prefix.) rrJr,r-rKrLrEr.r/KeyError SyntaxError r9msgrSrTrVchildrenrXrYattrss r:r~z _EtreeFrameParser._validate_paths  !  LL(((PE%*ErRZZ_ErEEHE$)HHbbiioo6GHdaQTHQHEH} o% ??x2~$S/)??u{$S/)r>erk$S/) +FH+& /  s)6C=C0 C=",C6A C=0 C==Dc|jr|jr,|jtt|j}nF|jj |j |j}||jdng}t|jr-t|jt|kr tdytt|jjdy)NrrB7names does not match length of child elements in xpath. is not a valid type for names)r0r6rjrkrfindr,r-rJrrorErgrhri)r9rparents r:rz!_EtreeFrameParser._validate_namess ::~~>>$tDNN/C*DE**4::$//*R282D6>>#."DJJ'tzz?S]2$Q3  DJJ'0011OP r<c$ddlm}m}t||j|j |j }t|5}||j}|||}ddd|jS#1swYjSxYw)Nr) XMLParserparsefilepath_or_bufferr4r8r&r4parser) rrrget_data_from_filepathr4r8r&preprocess_datagetroot)r9rrr handle_dataxml_data curr_parserdocuments r:rz_EtreeFrameParser._parse_docs -&]](( 00  [ ) ;X#T]];KXk:H ;!!  ;!!s A77BNrrr)rrrr)rirrrr@r~rrrr<r:rrs, ,'R("E" "r<rc@eZdZdZddZd dZd dZ d dZd dZy) _LxmlFrameParserz Internal class to parse XML into :class:`~pandas.DataFrame` with third-party full-featured XML library, ``lxml``, that supports ``XPath`` 1.0 and XSLT 1.0. cddlm}|jq|j|j|_|j r5|j|j |_|j|_|j}|j|j|j}|S|j|}|S)z Parse xml data. This method will call the other internal methods to validate ``xpath``, names, optionally parse and run XSLT, and parse original or transformed XML and return specific nodes. rr) lxml.etreer6rr(rr5xsl_doc_transform_docr~rr[r|rs r:r@z_LxmlFrameParser.parse_data!s ) >> !??4+>+>?DL#t? #224 '')E ~~%   e $  &&y1  r<cd}|jj|j|j}|Dcgc]}|jdD]}|}}}|Dcic]'}|jj D]\}}|| )}}}}|gk(r t ||gk7rM|j r|gk(r t ||jr|ik(r t ||gk(r|ik(r t ||Scc}}wcc}}}w)NrrrB)rr,r-rKrLrEr.r/rs r:r~z_LxmlFrameParser._validate_path>s !  ""4::$//"J!&?2#?2B?B?? %DD""))//2CD$!QADDD B;S/ ! B;8r> o%5B; o%2~%2+ o% @Ds C5!,C;c|jr|jr,|jtt|j}n4|jj |j dz|j }t|jr-t|jt|kr tdytt|jjdy)Nz[1]/*rrr) r0r6rjrkrr,r-rrorErgrhri)r9rs r:rz _LxmlFrameParser._validate_namesYs ::~~>>$tDNN/C*DE<<--JJ(T__.DJJ'tzz?S]2$Q3  DJJ'0011OP r<cddlm}m}m}t ||j |j |j}t|5}||j }t|tjrI|j td||jj|j |}n |||}ddd|S#1swYSxYw)Nr)r fromstringrrrz2Can not pass encoding None when input is StringIO.r)rrrrrr4r8r&rrfioStringIOrggetvalueencode) r9rrrrrrrrs r:rz_LxmlFrameParser._parse_docns  -&]](( 00  [ ) ?X#T]];K(BKK0==(#L&%%'..t}}=k!+> ? ?s BCCcZddlm}||j}||j}|S)z Transform original tree using stylesheet. This method will transform original xml using XSLT script into am ideally flatter xml document for easier parsing and migration to Data Frame. r)XSLT)rrrr)r9r transformernew_docs r:rz_LxmlFrameParser._transform_docs( $4<<( dll+r<Nrrr)rrrzetree._Element)rzetree._XSLTResultTree) rirrrr@r~rrrrr<r:rrs1 :6*E B r<rct|ts t|}t|tr|j dst|tr!t |st |s t|rWt|d|||5}t|jdr|jjn |j}ddd|S|S#1swY|SxYw)aG Extract raw XML data. The method accepts three input types: 1. filepath (string-like) 2. file-like object (e.g. open file object, StringIO) 3. XML string or bytes This method turns (1) into (2) to simplify the rest of the processing. It returns input types (2) and (3) unchanged. r_r)r4r8r&r^N) rfbytesrrmrnrrrrrlhandler^)rr4r8r& handle_objs r:rrs" (% 0+,>? %s+"--n= )3 / $ % + , ) *   #+   :,,f5!!&&(&&      s >=CCct|trtj|}|St|trtj |}|S)z Convert extracted raw data. This method will return underlying data of extracted XML content. The data either has a `read` attribute (e.g. a file object or a StringIO/BytesIO) or is a string or bytes that is an XML document. )rfrmrrrBytesIO)datas r:rrsB${{4  K D% zz$ Kr<c tt|}|Dcgc]}t|j}} t |fd|i|5}|j cdddScc}w#1swYyxYw#t $r t dwxYw)z Convert parsed data to Data Frame. This method will bind xml dictionary data of keys and values into named columns of Data Frame using the built-in TextParser class that build Data Frame and infers specific dtypes. r0NzqXML document may be too complex for import. Try to flatten document and use distinct element and attribute names.)rjrkrNrRrr^r )rkwargstagsrZnodestps r:_data_to_framers T D'+ ,!T!((*  ,E ,  4T 4V 4 779   -     +   s. A$A5 A) A5)A2.A52A55B c t|trWtt|t |t |t |gs$tjdtt| dk(r3tdd}|t|||||||||| | | | |}n4td| dk(rt|||||||||| | | | |}n td |j!}t#d |||||d |S) a Call internal parsers. This method will conditionally call internal parsers: LxmlFrameParser and/or EtreeParser. Raises ------ ImportError * If lxml is not installed if selected as parser. ValueError * If parser is not lxml or etree. zPassing literal xml to 'read_xml' is deprecated and will be removed in a future version. To read from a literal string, wrap it in a 'StringIO' object.) stacklevellxmlz lxml.etreeignore)errorsz7lxml not found, please install or use the etree parser.rz,Values for parser can only be lxml or etree.)rr1r2r3 dtype_backendr)rfrmanyrrrrwarningswarn FutureWarningr r r ImportErrorrrEr@r)r(r,r-r.r/r0r1r2r3r4rr5r6r8r&rrrp data_dictss r:_parsers7H.#&s  (  ' > " . )  0   > ')  ),xH   A"WX X 7                 "GHHJ   #     r<z./*Fzutf-8rra)r,r-r.r/r0r1r2r3r4rr5r6r8r&rct|tdid|d|d|d|d|d|d|d|d |d | d | d | d | d| d|d|S)aE' Read XML document into a :class:`~pandas.DataFrame` object. .. versionadded:: 1.3.0 Parameters ---------- path_or_buffer : str, path object, or file-like object String, path object (implementing ``os.PathLike[str]``), or file-like object implementing a ``read()`` function. The string can be any valid XML string or a path. The string can further be a URL. Valid URL schemes include http, ftp, s3, and file. .. deprecated:: 2.1.0 Passing xml literal strings is deprecated. Wrap literal xml input in ``io.StringIO`` or ``io.BytesIO`` instead. xpath : str, optional, default './\*' The ``XPath`` to parse required set of nodes for migration to :class:`~pandas.DataFrame`.``XPath`` should return a collection of elements and not a single element. Note: The ``etree`` parser supports limited ``XPath`` expressions. For more complex ``XPath``, use ``lxml`` which requires installation. namespaces : dict, optional The namespaces defined in XML document as dicts with key being namespace prefix and value the URI. There is no need to include all namespaces in XML, only the ones used in ``xpath`` expression. Note: if XML document uses default namespace denoted as `xmlns=''` without a prefix, you must assign any temporary namespace prefix such as 'doc' to the URI in order to parse underlying nodes and/or attributes. For example, :: namespaces = {{"doc": "https://example.com"}} elems_only : bool, optional, default False Parse only the child elements at the specified ``xpath``. By default, all child elements and non-empty text nodes are returned. attrs_only : bool, optional, default False Parse only the attributes at the specified ``xpath``. By default, all attributes are returned. names : list-like, optional Column names for DataFrame of parsed XML data. Use this parameter to rename original element names and distinguish same named elements and attributes. dtype : Type name or dict of column -> type, optional Data type for data or columns. E.g. {{'a': np.float64, 'b': np.int32, 'c': 'Int64'}} Use `str` or `object` together with suitable `na_values` settings to preserve and not interpret dtype. If converters are specified, they will be applied INSTEAD of dtype conversion. .. versionadded:: 1.5.0 converters : dict, optional Dict of functions for converting values in certain columns. Keys can either be integers or column labels. .. versionadded:: 1.5.0 parse_dates : bool or list of int or names or list of lists or dict, default False Identifiers to parse index or columns to datetime. The behavior is as follows: * boolean. If True -> try parsing the index. * list of int or names. e.g. If [1, 2, 3] -> try parsing columns 1, 2, 3 each as a separate date column. * list of lists. e.g. If [[1, 3]] -> combine columns 1 and 3 and parse as a single date column. * dict, e.g. {{'foo' : [1, 3]}} -> parse columns 1, 3 as date and call result 'foo' .. versionadded:: 1.5.0 encoding : str, optional, default 'utf-8' Encoding of XML document. parser : {{'lxml','etree'}}, default 'lxml' Parser module to use for retrieval of data. Only 'lxml' and 'etree' are supported. With 'lxml' more complex ``XPath`` searches and ability to use XSLT stylesheet are supported. stylesheet : str, path object or file-like object A URL, file-like object, or a raw string containing an XSLT script. This stylesheet should flatten complex, deeply nested XML documents for easier parsing. To use this feature you must have ``lxml`` module installed and specify 'lxml' as ``parser``. The ``xpath`` must reference nodes of transformed XML document generated after XSLT transformation and not the original XML document. Only XSLT 1.0 scripts and not later versions is currently supported. iterparse : dict, optional The nodes or attributes to retrieve in iterparsing of XML document as a dict with key being the name of repeating element and value being list of elements or attribute names that are descendants of the repeated element. Note: If this option is used, it will replace ``xpath`` parsing and unlike ``xpath``, descendants do not need to relate to each other but can exist any where in document under the repeating element. This memory- efficient method should be used for very large XML files (500MB, 1GB, or 5GB+). For example, :: iterparse = {{"row_element": ["child_elem", "attr", "grandchild_elem"]}} .. versionadded:: 1.5.0 {decompression_options} .. versionchanged:: 1.4.0 Zstandard support. {storage_options} dtype_backend : {{'numpy_nullable', 'pyarrow'}}, default 'numpy_nullable' Back-end data type applied to the resultant :class:`DataFrame` (still experimental). Behaviour is as follows: * ``"numpy_nullable"``: returns nullable-dtype-backed :class:`DataFrame` (default). * ``"pyarrow"``: returns pyarrow-backed nullable :class:`ArrowDtype` DataFrame. .. versionadded:: 2.0 Returns ------- df A DataFrame. See Also -------- read_json : Convert a JSON string to pandas object. read_html : Read HTML tables into a list of DataFrame objects. Notes ----- This method is best designed to import shallow XML documents in following format which is the ideal fit for the two-dimensions of a ``DataFrame`` (row by column). :: data data data ... ... ... As a file format, XML documents can be designed any way including layout of elements and attributes as long as it conforms to W3C specifications. Therefore, this method is a convenience handler for a specific flatter design and not all possible XML structures. However, for more complex XML documents, ``stylesheet`` allows you to temporarily redesign original document with XSLT (a special purpose language) for a flatter version for migration to a DataFrame. This function will *always* return a single :class:`DataFrame` or raise exceptions due to issues with XML document, ``xpath``, or other parameters. See the :ref:`read_xml documentation in the IO section of the docs ` for more information in using this method to parse XML files to DataFrames. Examples -------- >>> from io import StringIO >>> xml = ''' ... ... ... square ... 360 ... 4.0 ... ... ... circle ... 360 ... ... ... ... triangle ... 180 ... 3.0 ... ... ''' >>> df = pd.read_xml(StringIO(xml)) >>> df shape degrees sides 0 square 360 4.0 1 circle 360 NaN 2 triangle 180 3.0 >>> xml = ''' ... ... ... ... ... ''' >>> df = pd.read_xml(StringIO(xml), xpath=".//row") >>> df shape degrees sides 0 square 360 4.0 1 circle 360 NaN 2 triangle 180 3.0 >>> xml = ''' ... ... ... square ... 360 ... 4.0 ... ... ... circle ... 360 ... ... ... ... triangle ... 180 ... 3.0 ... ... ''' >>> df = pd.read_xml(StringIO(xml), ... xpath="//doc:row", ... namespaces={{"doc": "https://example.com"}}) >>> df shape degrees sides 0 square 360 4.0 1 circle 360 NaN 2 triangle 180 3.0 >>> xml_data = ''' ... ... ... 0 ... 1 ... 2.5 ... True ... a ... 2019-12-31 00:00:00 ... ... ... 1 ... 4.5 ... False ... b ... 2019-12-31 00:00:00 ... ... ... ''' >>> df = pd.read_xml(StringIO(xml_data), ... dtype_backend="numpy_nullable", ... parse_dates=["e"]) >>> df index a b c d e 0 0 1 2.5 True a 2019-12-31 1 1 4.5 False b 2019-12-31 r(r,r-r.r/r0r1r2r3r4rr5r6r8r&rr)rr)r(r,r-r.r/r0r1r2r3r4rr5r6r8r&rs r:read_xmlr`sL  &  %                     (  $! r<) rz6FilePath | bytes | ReadBuffer[bytes] | ReadBuffer[str]r4rr8rr&r#rz1str | bytes | ReadBuffer[bytes] | ReadBuffer[str])rzio.StringIO | io.BytesIO)rr%)"r(rr,rmr-rr.rr/rr0rr1rr2rr3rr4rrr$r5rr6rr8rr&r#rDtypeBackend | lib.NoDefaultrr%)"r(rr,rmr-rr.rr/rr0rr1rr2rr3rr4rrr$r5rr6rr8rr&zStorageOptions | Nonerrrr%)Ar __future__rrosrtypingrrrr pandas._libsrpandas.compat._optionalr pandas.errorsr r pandas.util._decoratorsr pandas.util._exceptionsr pandas.util._validatorsrpandas.core.dtypes.commonrpandas.core.shared_docsrpandas.io.commonrrrrrrrpandas.io.parsersrcollections.abcrrrrrpandas._typingrrrrr r!r"r#r$pandasr%r*rrrrr no_defaultrrrr<r:rs#  >(4720)(-   ! !23&'>?BRRf(f( f(R l"l"^BBJ*N**$*$ * 7 *Z$ N36..!hBh h&h h  h h h%h&hh hFh+h$h$h 0!h$%hV !23&'>?BRR(,"&!'+(,"HL-1&--125..%uBu u& u  u  u u u%u&uu uFu+u $!u"+#u$0%u&'u ur<