xml.py 36 KB

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