xml.py 38 KB

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