xml.py 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155
  1. """
  2. :mod:``pandas.io.xml`` is a module for reading XML.
  3. """
  4. from __future__ import annotations
  5. import io
  6. from os import PathLike
  7. from typing import (
  8. TYPE_CHECKING,
  9. Any,
  10. )
  11. from pandas._libs import lib
  12. from pandas.compat._optional import import_optional_dependency
  13. from pandas.errors import (
  14. AbstractMethodError,
  15. ParserError,
  16. )
  17. from pandas.util._decorators import set_module
  18. from pandas.util._validators import check_dtype_backend
  19. from pandas.core.dtypes.common import is_list_like
  20. from pandas.io.common import (
  21. get_handle,
  22. infer_compression,
  23. is_fsspec_url,
  24. is_url,
  25. stringify_path,
  26. )
  27. from pandas.io.parsers import TextParser
  28. if TYPE_CHECKING:
  29. from collections.abc import (
  30. Callable,
  31. Sequence,
  32. )
  33. from xml.etree.ElementTree import Element
  34. from lxml import etree
  35. from pandas._typing import (
  36. CompressionOptions,
  37. ConvertersArg,
  38. DtypeArg,
  39. DtypeBackend,
  40. FilePath,
  41. ParseDatesArg,
  42. ReadBuffer,
  43. StorageOptions,
  44. XMLParsers,
  45. )
  46. from pandas import DataFrame
  47. class _XMLFrameParser:
  48. """
  49. Internal subclass to parse XML into DataFrames.
  50. Parameters
  51. ----------
  52. path_or_buffer : a valid JSON ``str``, path object or file-like object
  53. Any valid string path is acceptable. The string could be a URL. Valid
  54. URL schemes include http, ftp, s3, and file.
  55. xpath : str or regex
  56. The ``XPath`` expression to parse required set of nodes for
  57. migration to :class:`~pandas.DataFrame`. ``etree`` supports limited ``XPath``.
  58. namespaces : dict
  59. The namespaces defined in XML document (``xmlns:namespace='URI'``)
  60. as dicts with key being namespace and value the URI.
  61. elems_only : bool
  62. Parse only the child elements at the specified ``xpath``.
  63. attrs_only : bool
  64. Parse only the attributes at the specified ``xpath``.
  65. names : list
  66. Column names for :class:`~pandas.DataFrame` of parsed XML data.
  67. dtype : dict
  68. Data type for data or columns. E.g. {{'a': np.float64,
  69. 'b': np.int32, 'c': 'Int64'}}
  70. converters : dict, optional
  71. Dict of functions for converting values in certain columns. Keys can
  72. either be integers or column labels.
  73. parse_dates : bool or list of int or names or list of lists or dict
  74. Converts either index or select columns to datetimes
  75. encoding : str
  76. Encoding of xml object or document.
  77. stylesheet : str or file-like
  78. URL, file, file-like object, or a raw string containing XSLT,
  79. ``etree`` does not support XSLT but retained for consistency.
  80. iterparse : dict, optional
  81. Dict with row element as key and list of descendant elements
  82. and/or attributes as value to be retrieved in iterparsing of
  83. XML document.
  84. compression : str or dict, default 'infer'
  85. For on-the-fly decompression of on-disk data. If 'infer' and
  86. 'path_or_buffer' is path-like, then detect compression from the
  87. following extensions: '.gz', '.bz2', '.zip', '.xz', '.zst', '.tar',
  88. '.tar.gz', '.tar.xz' or '.tar.bz2' (otherwise no compression).
  89. If using 'zip' or 'tar', the ZIP file must contain only one data
  90. file to be read in. Set to ``None`` for no decompression.
  91. Can also be a dict with key ``'method'`` set to one of
  92. {``'zip'``, ``'gzip'``, ``'bz2'``, ``'zstd'``, ``'xz'``, ``'tar'``}
  93. and other key-value pairs are forwarded to ``zipfile.ZipFile``,
  94. ``gzip.GzipFile``, ``bz2.BZ2File``, ``zstandard.ZstdDecompressor``,
  95. ``lzma.LZMAFile`` or ``tarfile.TarFile``, respectively.
  96. As an example, the following could be passed for Zstandard
  97. decompression using a custom compression dictionary:
  98. ``compression={'method': 'zstd', 'dict_data': my_compression_dict}``.
  99. storage_options : dict, optional
  100. Extra options that make sense for a particular storage connection,
  101. e.g. host, port, username, password, etc. For HTTP(S) URLs the
  102. key-value pairs are forwarded to ``urllib.request.Request`` as header
  103. options. For other URLs (e.g. starting with "s3://", and "gcs://")
  104. the key-value pairs are forwarded to ``fsspec.open``. Please see
  105. ``fsspec`` and ``urllib`` for more details, and for more examples on
  106. storage options refer `here <https://pandas.pydata.org/docs/
  107. user_guide/io.html?highlight=storage_options#reading-writing-remote-
  108. files>`_.
  109. See also
  110. --------
  111. pandas.io.xml._EtreeFrameParser
  112. pandas.io.xml._LxmlFrameParser
  113. Notes
  114. -----
  115. To subclass this class effectively you must override the following methods:`
  116. * :func:`parse_data`
  117. * :func:`_parse_nodes`
  118. * :func:`_iterparse_nodes`
  119. * :func:`_parse_doc`
  120. * :func:`_validate_names`
  121. * :func:`_validate_path`
  122. See each method's respective documentation for details on their
  123. functionality.
  124. """
  125. def __init__(
  126. self,
  127. path_or_buffer: FilePath | ReadBuffer[bytes] | ReadBuffer[str],
  128. xpath: str,
  129. namespaces: dict[str, str] | None,
  130. elems_only: bool,
  131. attrs_only: bool,
  132. names: Sequence[str] | None,
  133. dtype: DtypeArg | None,
  134. converters: ConvertersArg | None,
  135. parse_dates: ParseDatesArg | None,
  136. encoding: str | None,
  137. stylesheet: FilePath | ReadBuffer[bytes] | ReadBuffer[str] | None,
  138. iterparse: dict[str, list[str]] | None,
  139. compression: CompressionOptions,
  140. storage_options: StorageOptions,
  141. ) -> None:
  142. self.path_or_buffer = path_or_buffer
  143. self.xpath = xpath
  144. self.namespaces = namespaces
  145. self.elems_only = elems_only
  146. self.attrs_only = attrs_only
  147. self.names = names
  148. self.dtype = dtype
  149. self.converters = converters
  150. self.parse_dates = parse_dates
  151. self.encoding = encoding
  152. self.stylesheet = stylesheet
  153. self.iterparse = iterparse
  154. self.compression: CompressionOptions = compression
  155. self.storage_options = storage_options
  156. def parse_data(self) -> list[dict[str, str | None]]:
  157. """
  158. Parse xml data.
  159. This method will call the other internal methods to
  160. validate ``xpath``, names, parse and return specific nodes.
  161. """
  162. raise AbstractMethodError(self)
  163. def _parse_nodes(self, elems: list[Any]) -> list[dict[str, str | None]]:
  164. """
  165. Parse xml nodes.
  166. This method will parse the children and attributes of elements
  167. in ``xpath``, conditionally for only elements, only attributes
  168. or both while optionally renaming node names.
  169. Raises
  170. ------
  171. ValueError
  172. * If only elements and only attributes are specified.
  173. Notes
  174. -----
  175. Namespace URIs will be removed from return node values. Also,
  176. elements with missing children or attributes compared to siblings
  177. will have optional keys filled with None values.
  178. """
  179. dicts: list[dict[str, str | None]]
  180. if self.elems_only and self.attrs_only:
  181. raise ValueError("Either element or attributes can be parsed not both.")
  182. if self.elems_only:
  183. if self.names:
  184. dicts = [
  185. {
  186. **(
  187. {el.tag: el.text}
  188. if el.text and not el.text.isspace()
  189. else {}
  190. ),
  191. **{
  192. nm: ch.text if ch.text else None
  193. for nm, ch in zip(self.names, el.findall("*"), strict=True)
  194. },
  195. }
  196. for el in elems
  197. ]
  198. else:
  199. dicts = [
  200. {ch.tag: ch.text if ch.text else None for ch in el.findall("*")}
  201. for el in elems
  202. ]
  203. elif self.attrs_only:
  204. dicts = [
  205. {k: v if v else None for k, v in el.attrib.items()} for el in elems
  206. ]
  207. elif self.names:
  208. dicts = [
  209. {
  210. **el.attrib,
  211. **({el.tag: el.text} if el.text and not el.text.isspace() else {}),
  212. **{
  213. nm: ch.text if ch.text else None
  214. for nm, ch in zip(self.names, el.findall("*"), strict=False)
  215. },
  216. }
  217. for el in elems
  218. ]
  219. else:
  220. dicts = [
  221. {
  222. **el.attrib,
  223. **({el.tag: el.text} if el.text and not el.text.isspace() else {}),
  224. **{ch.tag: ch.text if ch.text else None for ch in el.findall("*")},
  225. }
  226. for el in elems
  227. ]
  228. dicts = [
  229. {k.split("}")[1] if "}" in k else k: v for k, v in d.items()} for d in dicts
  230. ]
  231. keys = list(dict.fromkeys([k for d in dicts for k in d.keys()]))
  232. dicts = [{k: d[k] if k in d.keys() else None for k in keys} for d in dicts]
  233. if self.names:
  234. dicts = [dict(zip(self.names, d.values(), strict=True)) for d in dicts]
  235. return dicts
  236. def _iterparse_nodes(self, iterparse: Callable) -> list[dict[str, str | None]]:
  237. """
  238. Iterparse xml nodes.
  239. This method will read in local disk, decompressed XML files for elements
  240. and underlying descendants using iterparse, a method to iterate through
  241. an XML tree without holding entire XML tree in memory.
  242. Raises
  243. ------
  244. TypeError
  245. * If ``iterparse`` is not a dict or its dict value is not list-like.
  246. ParserError
  247. * If ``path_or_buffer`` is not a physical file on disk or file-like object.
  248. * If no data is returned from selected items in ``iterparse``.
  249. Notes
  250. -----
  251. Namespace URIs will be removed from return node values. Also,
  252. elements with missing children or attributes in submitted list
  253. will have optional keys filled with None values.
  254. """
  255. dicts: list[dict[str, str | None]] = []
  256. row: dict[str, str | None] | None = None
  257. if not isinstance(self.iterparse, dict):
  258. raise TypeError(
  259. f"{type(self.iterparse).__name__} is not a valid type for iterparse"
  260. )
  261. row_node = next(iter(self.iterparse.keys())) if self.iterparse else ""
  262. if not is_list_like(self.iterparse[row_node]):
  263. raise TypeError(
  264. f"{type(self.iterparse[row_node])} is not a valid type "
  265. "for value in iterparse"
  266. )
  267. if (not hasattr(self.path_or_buffer, "read")) and (
  268. not isinstance(self.path_or_buffer, (str, PathLike))
  269. or is_url(self.path_or_buffer)
  270. or is_fsspec_url(self.path_or_buffer)
  271. or (
  272. isinstance(self.path_or_buffer, str)
  273. and self.path_or_buffer.startswith(("<?xml", "<"))
  274. )
  275. or infer_compression(self.path_or_buffer, "infer") is not None
  276. ):
  277. raise ParserError(
  278. "iterparse is designed for large XML files that are fully extracted on "
  279. "local disk and not as compressed files or online sources."
  280. )
  281. iterparse_repeats = len(self.iterparse[row_node]) != len(
  282. set(self.iterparse[row_node])
  283. )
  284. for event, elem in iterparse(self.path_or_buffer, events=("start", "end")):
  285. curr_elem = elem.tag.split("}")[1] if "}" in elem.tag else elem.tag
  286. if event == "start":
  287. if curr_elem == row_node:
  288. row = {}
  289. if row is not None:
  290. if self.names and iterparse_repeats:
  291. for col, nm in zip(
  292. self.iterparse[row_node], self.names, strict=True
  293. ):
  294. if curr_elem == col:
  295. elem_val = elem.text if elem.text else None
  296. if elem_val not in row.values() and nm not in row:
  297. row[nm] = elem_val
  298. if col in elem.attrib:
  299. if elem.attrib[col] not in row.values() and nm not in row:
  300. row[nm] = elem.attrib[col]
  301. else:
  302. for col in self.iterparse[row_node]:
  303. if curr_elem == col:
  304. row[col] = elem.text if elem.text else None
  305. if col in elem.attrib:
  306. row[col] = elem.attrib[col]
  307. if event == "end":
  308. if curr_elem == row_node and row is not None:
  309. dicts.append(row)
  310. row = None
  311. elem.clear()
  312. if hasattr(elem, "getprevious"):
  313. while (
  314. elem.getprevious() is not None and elem.getparent() is not None
  315. ):
  316. del elem.getparent()[0]
  317. if dicts == []:
  318. raise ParserError("No result from selected items in iterparse.")
  319. keys = list(dict.fromkeys([k for d in dicts for k in d.keys()]))
  320. dicts = [{k: d[k] if k in d.keys() else None for k in keys} for d in dicts]
  321. if self.names:
  322. dicts = [dict(zip(self.names, d.values(), strict=True)) for d in dicts]
  323. return dicts
  324. def _validate_path(self) -> list[Any]:
  325. """
  326. Validate ``xpath``.
  327. This method checks for syntax, evaluation, or empty nodes return.
  328. Raises
  329. ------
  330. SyntaxError
  331. * If xpah is not supported or issues with namespaces.
  332. ValueError
  333. * If xpah does not return any nodes.
  334. """
  335. raise AbstractMethodError(self)
  336. def _validate_names(self) -> None:
  337. """
  338. Validate names.
  339. This method will check if names is a list-like and aligns
  340. with length of parse nodes.
  341. Raises
  342. ------
  343. ValueError
  344. * If value is not a list and less then length of nodes.
  345. """
  346. raise AbstractMethodError(self)
  347. def _parse_doc(
  348. self, raw_doc: FilePath | ReadBuffer[bytes] | ReadBuffer[str]
  349. ) -> Element | etree._Element:
  350. """
  351. Build tree from path_or_buffer.
  352. This method will parse XML object into tree
  353. either from string/bytes or file location.
  354. """
  355. raise AbstractMethodError(self)
  356. class _EtreeFrameParser(_XMLFrameParser):
  357. """
  358. Internal class to parse XML into DataFrames with the Python
  359. standard library XML module: `xml.etree.ElementTree`.
  360. """
  361. def parse_data(self) -> list[dict[str, str | None]]:
  362. from xml.etree.ElementTree import iterparse
  363. if self.stylesheet is not None:
  364. raise ValueError(
  365. "To use stylesheet, you need lxml installed and selected as parser."
  366. )
  367. if self.iterparse is None:
  368. self.xml_doc = self._parse_doc(self.path_or_buffer)
  369. elems = self._validate_path()
  370. self._validate_names()
  371. xml_dicts: list[dict[str, str | None]] = (
  372. self._parse_nodes(elems)
  373. if self.iterparse is None
  374. else self._iterparse_nodes(iterparse)
  375. )
  376. return xml_dicts
  377. def _validate_path(self) -> list[Any]:
  378. """
  379. Notes
  380. -----
  381. ``etree`` supports limited ``XPath``. If user attempts a more complex
  382. expression syntax error will raise.
  383. """
  384. msg = (
  385. "xpath does not return any nodes or attributes. "
  386. "Be sure to specify in `xpath` the parent nodes of "
  387. "children and attributes to parse. "
  388. "If document uses namespaces denoted with "
  389. "xmlns, be sure to define namespaces and "
  390. "use them in xpath."
  391. )
  392. try:
  393. elems = self.xml_doc.findall(self.xpath, namespaces=self.namespaces)
  394. children = [ch for el in elems for ch in el.findall("*")]
  395. attrs = {k: v for el in elems for k, v in el.attrib.items()}
  396. if elems is None:
  397. raise ValueError(msg)
  398. if elems is not None:
  399. if self.elems_only and children == []:
  400. raise ValueError(msg)
  401. if self.attrs_only and attrs == {}:
  402. raise ValueError(msg)
  403. if children == [] and attrs == {}:
  404. raise ValueError(msg)
  405. except (KeyError, SyntaxError) as err:
  406. raise SyntaxError(
  407. "You have used an incorrect or unsupported XPath "
  408. "expression for etree library or you used an "
  409. "undeclared namespace prefix."
  410. ) from err
  411. return elems
  412. def _validate_names(self) -> None:
  413. children: list[Any]
  414. if self.names:
  415. if self.iterparse:
  416. children = self.iterparse[next(iter(self.iterparse))]
  417. else:
  418. parent = self.xml_doc.find(self.xpath, namespaces=self.namespaces)
  419. children = parent.findall("*") if parent is not None else []
  420. if is_list_like(self.names):
  421. if len(self.names) < len(children):
  422. raise ValueError(
  423. "names does not match length of child elements in xpath."
  424. )
  425. else:
  426. raise TypeError(
  427. f"{type(self.names).__name__} is not a valid type for names"
  428. )
  429. def _parse_doc(
  430. self, raw_doc: FilePath | ReadBuffer[bytes] | ReadBuffer[str]
  431. ) -> Element:
  432. from xml.etree.ElementTree import (
  433. XMLParser,
  434. parse,
  435. )
  436. handle_data = get_data_from_filepath(
  437. filepath_or_buffer=raw_doc,
  438. encoding=self.encoding,
  439. compression=self.compression,
  440. storage_options=self.storage_options,
  441. )
  442. with handle_data as xml_data:
  443. curr_parser = XMLParser(encoding=self.encoding)
  444. document = parse(xml_data, parser=curr_parser)
  445. return document.getroot()
  446. class _LxmlFrameParser(_XMLFrameParser):
  447. """
  448. Internal class to parse XML into :class:`~pandas.DataFrame` with third-party
  449. full-featured XML library, ``lxml``, that supports
  450. ``XPath`` 1.0 and XSLT 1.0.
  451. """
  452. def parse_data(self) -> list[dict[str, str | None]]:
  453. """
  454. Parse xml data.
  455. This method will call the other internal methods to
  456. validate ``xpath``, names, optionally parse and run XSLT,
  457. and parse original or transformed XML and return specific nodes.
  458. """
  459. from lxml.etree import iterparse
  460. if self.iterparse is None:
  461. self.xml_doc = self._parse_doc(self.path_or_buffer)
  462. if self.stylesheet:
  463. self.xsl_doc = self._parse_doc(self.stylesheet)
  464. self.xml_doc = self._transform_doc()
  465. elems = self._validate_path()
  466. self._validate_names()
  467. xml_dicts: list[dict[str, str | None]] = (
  468. self._parse_nodes(elems)
  469. if self.iterparse is None
  470. else self._iterparse_nodes(iterparse)
  471. )
  472. return xml_dicts
  473. def _validate_path(self) -> list[Any]:
  474. msg = (
  475. "xpath does not return any nodes or attributes. "
  476. "Be sure to specify in `xpath` the parent nodes of "
  477. "children and attributes to parse. "
  478. "If document uses namespaces denoted with "
  479. "xmlns, be sure to define namespaces and "
  480. "use them in xpath."
  481. )
  482. elems = self.xml_doc.xpath(self.xpath, namespaces=self.namespaces)
  483. children = [ch for el in elems for ch in el.xpath("*")]
  484. attrs = {k: v for el in elems for k, v in el.attrib.items()}
  485. if elems == []:
  486. raise ValueError(msg)
  487. if elems != []:
  488. if self.elems_only and children == []:
  489. raise ValueError(msg)
  490. if self.attrs_only and attrs == {}:
  491. raise ValueError(msg)
  492. if children == [] and attrs == {}:
  493. raise ValueError(msg)
  494. return elems
  495. def _validate_names(self) -> None:
  496. children: list[Any]
  497. if self.names:
  498. if self.iterparse:
  499. children = self.iterparse[next(iter(self.iterparse))]
  500. else:
  501. children = self.xml_doc.xpath(
  502. self.xpath + "[1]/*", namespaces=self.namespaces
  503. )
  504. if is_list_like(self.names):
  505. if len(self.names) < len(children):
  506. raise ValueError(
  507. "names does not match length of child elements in xpath."
  508. )
  509. else:
  510. raise TypeError(
  511. f"{type(self.names).__name__} is not a valid type for names"
  512. )
  513. def _parse_doc(
  514. self, raw_doc: FilePath | ReadBuffer[bytes] | ReadBuffer[str]
  515. ) -> etree._Element:
  516. from lxml.etree import (
  517. XMLParser,
  518. fromstring,
  519. parse,
  520. )
  521. handle_data = get_data_from_filepath(
  522. filepath_or_buffer=raw_doc,
  523. encoding=self.encoding,
  524. compression=self.compression,
  525. storage_options=self.storage_options,
  526. )
  527. with handle_data as xml_data:
  528. curr_parser = XMLParser(encoding=self.encoding)
  529. if isinstance(xml_data, io.StringIO):
  530. if self.encoding is None:
  531. raise TypeError(
  532. "Can not pass encoding None when input is StringIO."
  533. )
  534. document = fromstring(
  535. xml_data.getvalue().encode(self.encoding), parser=curr_parser
  536. )
  537. else:
  538. document = parse(xml_data, parser=curr_parser)
  539. return document
  540. def _transform_doc(self) -> etree._XSLTResultTree:
  541. """
  542. Transform original tree using stylesheet.
  543. This method will transform original xml using XSLT script into
  544. am ideally flatter xml document for easier parsing and migration
  545. to Data Frame.
  546. """
  547. from lxml.etree import XSLT
  548. transformer = XSLT(self.xsl_doc)
  549. new_doc = transformer(self.xml_doc)
  550. return new_doc
  551. def get_data_from_filepath(
  552. filepath_or_buffer: FilePath | ReadBuffer[bytes] | ReadBuffer[str],
  553. encoding: str | None,
  554. compression: CompressionOptions,
  555. storage_options: StorageOptions,
  556. ):
  557. """
  558. Extract raw XML data.
  559. The method accepts two input types:
  560. 1. filepath (string-like)
  561. 2. file-like object (e.g. open file object, StringIO)
  562. """
  563. filepath_or_buffer = stringify_path(filepath_or_buffer)
  564. with get_handle(
  565. filepath_or_buffer,
  566. "r",
  567. encoding=encoding,
  568. compression=compression,
  569. storage_options=storage_options,
  570. ) as handle_obj:
  571. return (
  572. preprocess_data(handle_obj.handle.read())
  573. if hasattr(handle_obj.handle, "read")
  574. else handle_obj.handle
  575. )
  576. def preprocess_data(
  577. data: str | bytes | io.StringIO | io.BytesIO,
  578. ) -> io.StringIO | io.BytesIO:
  579. """
  580. Convert extracted raw data.
  581. This method will return underlying data of extracted XML content.
  582. The data either has a `read` attribute (e.g. a file object or a
  583. StringIO/BytesIO) or is a string or bytes that is an XML document.
  584. """
  585. if isinstance(data, str):
  586. data = io.StringIO(data)
  587. elif isinstance(data, bytes):
  588. data = io.BytesIO(data)
  589. return data
  590. def _data_to_frame(data: list[dict[str, str | None]], **kwargs) -> DataFrame:
  591. """
  592. Convert parsed data to Data Frame.
  593. This method will bind xml dictionary data of keys and values
  594. into named columns of Data Frame using the built-in TextParser
  595. class that build Data Frame and infers specific dtypes.
  596. """
  597. tags = next(iter(data))
  598. nodes = [list(d.values()) for d in data]
  599. try:
  600. with TextParser(nodes, names=tags, **kwargs) as tp:
  601. return tp.read()
  602. except ParserError as err:
  603. raise ParserError(
  604. "XML document may be too complex for import. "
  605. "Try to flatten document and use distinct "
  606. "element and attribute names."
  607. ) from err
  608. def _parse(
  609. path_or_buffer: FilePath | ReadBuffer[bytes] | ReadBuffer[str],
  610. xpath: str,
  611. namespaces: dict[str, str] | None,
  612. elems_only: bool,
  613. attrs_only: bool,
  614. names: Sequence[str] | None,
  615. dtype: DtypeArg | None,
  616. converters: ConvertersArg | None,
  617. parse_dates: ParseDatesArg | None,
  618. encoding: str | None,
  619. parser: XMLParsers,
  620. stylesheet: FilePath | ReadBuffer[bytes] | ReadBuffer[str] | None,
  621. iterparse: dict[str, list[str]] | None,
  622. compression: CompressionOptions,
  623. storage_options: StorageOptions,
  624. dtype_backend: DtypeBackend | lib.NoDefault = lib.no_default,
  625. **kwargs,
  626. ) -> DataFrame:
  627. """
  628. Call internal parsers.
  629. This method will conditionally call internal parsers:
  630. LxmlFrameParser and/or EtreeParser.
  631. Raises
  632. ------
  633. ImportError
  634. * If lxml is not installed if selected as parser.
  635. ValueError
  636. * If parser is not lxml or etree.
  637. """
  638. p: _EtreeFrameParser | _LxmlFrameParser
  639. if parser == "lxml":
  640. lxml = import_optional_dependency("lxml.etree", errors="ignore")
  641. if lxml is not None:
  642. p = _LxmlFrameParser(
  643. path_or_buffer,
  644. xpath,
  645. namespaces,
  646. elems_only,
  647. attrs_only,
  648. names,
  649. dtype,
  650. converters,
  651. parse_dates,
  652. encoding,
  653. stylesheet,
  654. iterparse,
  655. compression,
  656. storage_options,
  657. )
  658. else:
  659. raise ImportError("lxml not found, please install or use the etree parser.")
  660. elif parser == "etree":
  661. p = _EtreeFrameParser(
  662. path_or_buffer,
  663. xpath,
  664. namespaces,
  665. elems_only,
  666. attrs_only,
  667. names,
  668. dtype,
  669. converters,
  670. parse_dates,
  671. encoding,
  672. stylesheet,
  673. iterparse,
  674. compression,
  675. storage_options,
  676. )
  677. else:
  678. raise ValueError("Values for parser can only be lxml or etree.")
  679. data_dicts = p.parse_data()
  680. return _data_to_frame(
  681. data=data_dicts,
  682. dtype=dtype,
  683. converters=converters,
  684. parse_dates=parse_dates,
  685. dtype_backend=dtype_backend,
  686. **kwargs,
  687. )
  688. @set_module("pandas")
  689. def read_xml(
  690. path_or_buffer: FilePath | ReadBuffer[bytes] | ReadBuffer[str],
  691. *,
  692. xpath: str = "./*",
  693. namespaces: dict[str, str] | None = None,
  694. elems_only: bool = False,
  695. attrs_only: bool = False,
  696. names: Sequence[str] | None = None,
  697. dtype: DtypeArg | None = None,
  698. converters: ConvertersArg | None = None,
  699. parse_dates: ParseDatesArg | None = None,
  700. # encoding can not be None for lxml and StringIO input
  701. encoding: str | None = "utf-8",
  702. parser: XMLParsers = "lxml",
  703. stylesheet: FilePath | ReadBuffer[bytes] | ReadBuffer[str] | None = None,
  704. iterparse: dict[str, list[str]] | None = None,
  705. compression: CompressionOptions = "infer",
  706. storage_options: StorageOptions | None = None,
  707. dtype_backend: DtypeBackend | lib.NoDefault = lib.no_default,
  708. ) -> DataFrame:
  709. r"""
  710. Read XML document into a :class:`~pandas.DataFrame` object.
  711. Parameters
  712. ----------
  713. path_or_buffer : str, path object, or file-like object
  714. String path, path object (implementing ``os.PathLike[str]``), or file-like
  715. object implementing a ``read()`` function. The string can be a path.
  716. The string can further be a URL. Valid URL schemes
  717. include http, ftp, s3, and file.
  718. xpath : str, optional, default './\*'
  719. The ``XPath`` to parse required set of nodes for migration to
  720. :class:`~pandas.DataFrame`.``XPath`` should return a collection of elements
  721. and not a single element. Note: The ``etree`` parser supports limited ``XPath``
  722. expressions. For more complex ``XPath``, use ``lxml`` which requires
  723. installation.
  724. namespaces : dict, optional
  725. The namespaces defined in XML document as dicts with key being
  726. namespace prefix and value the URI. There is no need to include all
  727. namespaces in XML, only the ones used in ``xpath`` expression.
  728. Note: if XML document uses default namespace denoted as
  729. `xmlns='<URI>'` without a prefix, you must assign any temporary
  730. namespace prefix such as 'doc' to the URI in order to parse
  731. underlying nodes and/or attributes.
  732. elems_only : bool, optional, default False
  733. Parse only the child elements at the specified ``xpath``. By default,
  734. all child elements and non-empty text nodes are returned.
  735. attrs_only : bool, optional, default False
  736. Parse only the attributes at the specified ``xpath``.
  737. By default, all attributes are returned.
  738. names : list-like, optional
  739. Column names for DataFrame of parsed XML data. Use this parameter to
  740. rename original element names and distinguish same named elements and
  741. attributes.
  742. dtype : Type name or dict of column -> type, optional
  743. Data type for data or columns. E.g. {{'a': np.float64, 'b': np.int32,
  744. 'c': 'Int64'}}
  745. Use `str` or `object` together with suitable `na_values` settings
  746. to preserve and not interpret dtype.
  747. If converters are specified, they will be applied INSTEAD
  748. of dtype conversion.
  749. converters : dict, optional
  750. Dict of functions for converting values in certain columns. Keys can either
  751. be integers or column labels.
  752. parse_dates : bool or list of int or names or list of lists or dict, default False
  753. Identifiers to parse index or columns to datetime. The behavior is as follows:
  754. * boolean. If True -> try parsing the index.
  755. * list of int or names. e.g. If [1, 2, 3] -> try parsing columns 1, 2, 3
  756. each as a separate date column.
  757. * list of lists. e.g. If [[1, 3]] -> combine columns 1 and 3 and parse as
  758. a single date column.
  759. * dict, e.g. {{'foo' : [1, 3]}} -> parse columns 1, 3 as date and call
  760. result 'foo'
  761. encoding : str, optional, default 'utf-8'
  762. Encoding of XML document.
  763. parser : {{'lxml','etree'}}, default 'lxml'
  764. Parser module to use for retrieval of data. Only 'lxml' and
  765. 'etree' are supported. With 'lxml' more complex ``XPath`` searches
  766. and ability to use XSLT stylesheet are supported.
  767. stylesheet : str, path object or file-like object
  768. A URL, file-like object, or a string path containing an XSLT script.
  769. This stylesheet should flatten complex, deeply nested XML documents
  770. for easier parsing. To use this feature you must have ``lxml`` module
  771. installed and specify 'lxml' as ``parser``. The ``xpath`` must
  772. reference nodes of transformed XML document generated after XSLT
  773. transformation and not the original XML document. Only XSLT 1.0
  774. scripts and not later versions is currently supported.
  775. iterparse : dict, optional
  776. The nodes or attributes to retrieve in iterparsing of XML document
  777. as a dict with key being the name of repeating element and value being
  778. list of elements or attribute names that are descendants of the repeated
  779. element. Note: If this option is used, it will replace ``xpath`` parsing
  780. and unlike ``xpath``, descendants do not need to relate to each other but can
  781. exist any where in document under the repeating element. This memory-
  782. efficient method should be used for very large XML files (500MB, 1GB, or 5GB+).
  783. For example, ``{{"row_element": ["child_elem", "attr", "grandchild_elem"]}}``.
  784. compression : str or dict, default 'infer'
  785. For on-the-fly decompression of on-disk data. If 'infer' and
  786. 'path_or_buffer' is path-like, then detect compression from the
  787. following extensions: '.gz', '.bz2', '.zip', '.xz', '.zst', '.tar',
  788. '.tar.gz', '.tar.xz' or '.tar.bz2' (otherwise no compression).
  789. If using 'zip' or 'tar', the ZIP file must contain only one data
  790. file to be read in. Set to ``None`` for no decompression.
  791. Can also be a dict with key ``'method'`` set to one of
  792. {``'zip'``, ``'gzip'``, ``'bz2'``, ``'zstd'``, ``'xz'``, ``'tar'``}
  793. and other key-value pairs are forwarded to ``zipfile.ZipFile``,
  794. ``gzip.GzipFile``, ``bz2.BZ2File``, ``zstandard.ZstdDecompressor``,
  795. ``lzma.LZMAFile`` or ``tarfile.TarFile``, respectively.
  796. As an example, the following could be passed for Zstandard
  797. decompression using a custom compression dictionary:
  798. ``compression={'method': 'zstd', 'dict_data': my_compression_dict}``.
  799. storage_options : dict, optional
  800. Extra options that make sense for a particular storage connection,
  801. e.g. host, port, username, password, etc. For HTTP(S) URLs the
  802. key-value pairs are forwarded to ``urllib.request.Request`` as header
  803. options. For other URLs (e.g. starting with "s3://", and "gcs://")
  804. the key-value pairs are forwarded to ``fsspec.open``. Please see
  805. ``fsspec`` and ``urllib`` for more details, and for more examples on
  806. storage options refer `here <https://pandas.pydata.org/docs/
  807. user_guide/io.html?highlight=storage_options#reading-writing-remote-
  808. files>`_.
  809. dtype_backend : {{'numpy_nullable', 'pyarrow'}}
  810. Back-end data type applied to the resultant :class:`DataFrame`
  811. (still experimental). If not specified, the default behavior
  812. is to not use nullable data types. If specified, the behavior
  813. is as follows:
  814. * ``"numpy_nullable"``: returns nullable-dtype-backed :class:`DataFrame`
  815. * ``"pyarrow"``: returns pyarrow-backed nullable
  816. :class:`ArrowDtype` :class:`DataFrame`
  817. .. versionadded:: 2.0
  818. Returns
  819. -------
  820. df
  821. A DataFrame.
  822. See Also
  823. --------
  824. read_json : Convert a JSON string to pandas object.
  825. read_html : Read HTML tables into a list of DataFrame objects.
  826. Notes
  827. -----
  828. This method is best designed to import shallow XML documents in
  829. following format which is the ideal fit for the two-dimensions of a
  830. ``DataFrame`` (row by column). ::
  831. <root>
  832. <row>
  833. <column1>data</column1>
  834. <column2>data</column2>
  835. <column3>data</column3>
  836. ...
  837. </row>
  838. <row>
  839. ...
  840. </row>
  841. ...
  842. </root>
  843. As a file format, XML documents can be designed any way including
  844. layout of elements and attributes as long as it conforms to W3C
  845. specifications. Therefore, this method is a convenience handler for
  846. a specific flatter design and not all possible XML structures.
  847. However, for more complex XML documents, ``stylesheet`` allows you to
  848. temporarily redesign original document with XSLT (a special purpose
  849. language) for a flatter version for migration to a DataFrame.
  850. This function will *always* return a single :class:`DataFrame` or raise
  851. exceptions due to issues with XML document, ``xpath``, or other
  852. parameters.
  853. See the :ref:`read_xml documentation in the IO section of the docs
  854. <io.read_xml>` for more information in using this method to parse XML
  855. files to DataFrames.
  856. Examples
  857. --------
  858. >>> from io import StringIO
  859. >>> xml = '''<?xml version='1.0' encoding='utf-8'?>
  860. ... <data xmlns="http://example.com">
  861. ... <row>
  862. ... <shape>square</shape>
  863. ... <degrees>360</degrees>
  864. ... <sides>4.0</sides>
  865. ... </row>
  866. ... <row>
  867. ... <shape>circle</shape>
  868. ... <degrees>360</degrees>
  869. ... <sides/>
  870. ... </row>
  871. ... <row>
  872. ... <shape>triangle</shape>
  873. ... <degrees>180</degrees>
  874. ... <sides>3.0</sides>
  875. ... </row>
  876. ... </data>'''
  877. >>> df = pd.read_xml(StringIO(xml))
  878. >>> df
  879. shape degrees sides
  880. 0 square 360 4.0
  881. 1 circle 360 NaN
  882. 2 triangle 180 3.0
  883. >>> xml = '''<?xml version='1.0' encoding='utf-8'?>
  884. ... <data>
  885. ... <row shape="square" degrees="360" sides="4.0"/>
  886. ... <row shape="circle" degrees="360"/>
  887. ... <row shape="triangle" degrees="180" sides="3.0"/>
  888. ... </data>'''
  889. >>> df = pd.read_xml(StringIO(xml), xpath=".//row")
  890. >>> df
  891. shape degrees sides
  892. 0 square 360 4.0
  893. 1 circle 360 NaN
  894. 2 triangle 180 3.0
  895. >>> xml = '''<?xml version='1.0' encoding='utf-8'?>
  896. ... <doc:data xmlns:doc="https://example.com">
  897. ... <doc:row>
  898. ... <doc:shape>square</doc:shape>
  899. ... <doc:degrees>360</doc:degrees>
  900. ... <doc:sides>4.0</doc:sides>
  901. ... </doc:row>
  902. ... <doc:row>
  903. ... <doc:shape>circle</doc:shape>
  904. ... <doc:degrees>360</doc:degrees>
  905. ... <doc:sides/>
  906. ... </doc:row>
  907. ... <doc:row>
  908. ... <doc:shape>triangle</doc:shape>
  909. ... <doc:degrees>180</doc:degrees>
  910. ... <doc:sides>3.0</doc:sides>
  911. ... </doc:row>
  912. ... </doc:data>'''
  913. >>> df = pd.read_xml(
  914. ... StringIO(xml),
  915. ... xpath="//doc:row",
  916. ... namespaces={"doc": "https://example.com"},
  917. ... )
  918. >>> df
  919. shape degrees sides
  920. 0 square 360 4.0
  921. 1 circle 360 NaN
  922. 2 triangle 180 3.0
  923. >>> xml_data = '''
  924. ... <data>
  925. ... <row>
  926. ... <index>0</index>
  927. ... <a>1</a>
  928. ... <b>2.5</b>
  929. ... <c>True</c>
  930. ... <d>a</d>
  931. ... <e>2019-12-31 00:00:00</e>
  932. ... </row>
  933. ... <row>
  934. ... <index>1</index>
  935. ... <b>4.5</b>
  936. ... <c>False</c>
  937. ... <d>b</d>
  938. ... <e>2019-12-31 00:00:00</e>
  939. ... </row>
  940. ... </data>
  941. ... '''
  942. >>> df = pd.read_xml(
  943. ... StringIO(xml_data), dtype_backend="numpy_nullable", parse_dates=["e"]
  944. ... )
  945. >>> df
  946. index a b c d e
  947. 0 0 1 2.5 True a 2019-12-31
  948. 1 1 <NA> 4.5 False b 2019-12-31
  949. """
  950. check_dtype_backend(dtype_backend)
  951. return _parse(
  952. path_or_buffer=path_or_buffer,
  953. xpath=xpath,
  954. namespaces=namespaces,
  955. elems_only=elems_only,
  956. attrs_only=attrs_only,
  957. names=names,
  958. dtype=dtype,
  959. converters=converters,
  960. parse_dates=parse_dates,
  961. encoding=encoding,
  962. parser=parser,
  963. stylesheet=stylesheet,
  964. iterparse=iterparse,
  965. compression=compression,
  966. storage_options=storage_options,
  967. dtype_backend=dtype_backend,
  968. )