test_xml.py 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079
  1. from __future__ import annotations
  2. from io import (
  3. BytesIO,
  4. StringIO,
  5. )
  6. from lzma import LZMAError
  7. import os
  8. from tarfile import ReadError
  9. from urllib.error import HTTPError
  10. from xml.etree.ElementTree import ParseError
  11. from zipfile import BadZipFile
  12. import numpy as np
  13. import pytest
  14. from pandas.compat._optional import import_optional_dependency
  15. from pandas.errors import (
  16. EmptyDataError,
  17. ParserError,
  18. )
  19. import pandas.util._test_decorators as td
  20. import pandas as pd
  21. from pandas import (
  22. NA,
  23. DataFrame,
  24. Series,
  25. )
  26. import pandas._testing as tm
  27. from pandas.io.common import get_handle
  28. from pandas.io.xml import read_xml
  29. # CHECK LIST
  30. # [x] - ValueError: "Values for parser can only be lxml or etree."
  31. # etree
  32. # [X] - ImportError: "lxml not found, please install or use the etree parser."
  33. # [X] - TypeError: "expected str, bytes or os.PathLike object, not NoneType"
  34. # [X] - ValueError: "Either element or attributes can be parsed not both."
  35. # [X] - ValueError: "xpath does not return any nodes..."
  36. # [X] - SyntaxError: "You have used an incorrect or unsupported XPath"
  37. # [X] - ValueError: "names does not match length of child elements in xpath."
  38. # [X] - TypeError: "...is not a valid type for names"
  39. # [X] - ValueError: "To use stylesheet, you need lxml installed..."
  40. # [] - URLError: (GENERAL ERROR WITH HTTPError AS SUBCLASS)
  41. # [X] - HTTPError: "HTTP Error 404: Not Found"
  42. # [] - OSError: (GENERAL ERROR WITH FileNotFoundError AS SUBCLASS)
  43. # [X] - FileNotFoundError: "No such file or directory"
  44. # [] - ParseError (FAILSAFE CATCH ALL FOR VERY COMPLEX XML)
  45. # [X] - UnicodeDecodeError: "'utf-8' codec can't decode byte 0xe9..."
  46. # [X] - UnicodeError: "UTF-16 stream does not start with BOM"
  47. # [X] - BadZipFile: "File is not a zip file"
  48. # [X] - OSError: "Invalid data stream"
  49. # [X] - LZMAError: "Input format not supported by decoder"
  50. # [X] - ValueError: "Unrecognized compression type"
  51. # [X] - PermissionError: "Forbidden"
  52. # lxml
  53. # [X] - ValueError: "Either element or attributes can be parsed not both."
  54. # [X] - AttributeError: "__enter__"
  55. # [X] - XSLTApplyError: "Cannot resolve URI"
  56. # [X] - XSLTParseError: "document is not a stylesheet"
  57. # [X] - ValueError: "xpath does not return any nodes."
  58. # [X] - XPathEvalError: "Invalid expression"
  59. # [] - XPathSyntaxError: (OLD VERSION IN lxml FOR XPATH ERRORS)
  60. # [X] - TypeError: "empty namespace prefix is not supported in XPath"
  61. # [X] - ValueError: "names does not match length of child elements in xpath."
  62. # [X] - TypeError: "...is not a valid type for names"
  63. # [X] - LookupError: "unknown encoding"
  64. # [] - URLError: (USUALLY DUE TO NETWORKING)
  65. # [X - HTTPError: "HTTP Error 404: Not Found"
  66. # [X] - OSError: "failed to load external entity"
  67. # [X] - XMLSyntaxError: "Start tag expected, '<' not found"
  68. # [] - ParserError: (FAILSAFE CATCH ALL FOR VERY COMPLEX XML
  69. # [X] - ValueError: "Values for parser can only be lxml or etree."
  70. # [X] - UnicodeDecodeError: "'utf-8' codec can't decode byte 0xe9..."
  71. # [X] - UnicodeError: "UTF-16 stream does not start with BOM"
  72. # [X] - BadZipFile: "File is not a zip file"
  73. # [X] - OSError: "Invalid data stream"
  74. # [X] - LZMAError: "Input format not supported by decoder"
  75. # [X] - ValueError: "Unrecognized compression type"
  76. # [X] - PermissionError: "Forbidden"
  77. geom_df = DataFrame(
  78. {
  79. "shape": ["square", "circle", "triangle"],
  80. "degrees": [360, 360, 180],
  81. "sides": [4, np.nan, 3],
  82. }
  83. )
  84. xml_default_nmsp = """\
  85. <?xml version='1.0' encoding='utf-8'?>
  86. <data xmlns="http://example.com">
  87. <row>
  88. <shape>square</shape>
  89. <degrees>360</degrees>
  90. <sides>4</sides>
  91. </row>
  92. <row>
  93. <shape>circle</shape>
  94. <degrees>360</degrees>
  95. <sides/>
  96. </row>
  97. <row>
  98. <shape>triangle</shape>
  99. <degrees>180</degrees>
  100. <sides>3</sides>
  101. </row>
  102. </data>"""
  103. xml_prefix_nmsp = """\
  104. <?xml version='1.0' encoding='utf-8'?>
  105. <doc:data xmlns:doc="http://example.com">
  106. <doc:row>
  107. <doc:shape>square</doc:shape>
  108. <doc:degrees>360</doc:degrees>
  109. <doc:sides>4.0</doc:sides>
  110. </doc:row>
  111. <doc:row>
  112. <doc:shape>circle</doc:shape>
  113. <doc:degrees>360</doc:degrees>
  114. <doc:sides/>
  115. </doc:row>
  116. <doc:row>
  117. <doc:shape>triangle</doc:shape>
  118. <doc:degrees>180</doc:degrees>
  119. <doc:sides>3.0</doc:sides>
  120. </doc:row>
  121. </doc:data>"""
  122. df_kml = DataFrame(
  123. {
  124. "id": {
  125. 0: "ID_00001",
  126. 1: "ID_00002",
  127. 2: "ID_00003",
  128. 3: "ID_00004",
  129. 4: "ID_00005",
  130. },
  131. "name": {
  132. 0: "Blue Line (Forest Park)",
  133. 1: "Red, Purple Line",
  134. 2: "Red, Purple Line",
  135. 3: "Red, Purple Line",
  136. 4: "Red, Purple Line",
  137. },
  138. "styleUrl": {
  139. 0: "#LineStyle01",
  140. 1: "#LineStyle01",
  141. 2: "#LineStyle01",
  142. 3: "#LineStyle01",
  143. 4: "#LineStyle01",
  144. },
  145. "extrude": {0: 0, 1: 0, 2: 0, 3: 0, 4: 0},
  146. "altitudeMode": {
  147. 0: "clampedToGround",
  148. 1: "clampedToGround",
  149. 2: "clampedToGround",
  150. 3: "clampedToGround",
  151. 4: "clampedToGround",
  152. },
  153. "coordinates": {
  154. 0: (
  155. "-87.77678526964958,41.8708863930319,0 "
  156. "-87.77826234150609,41.87097820122218,0 "
  157. "-87.78251583439344,41.87130129991005,0 "
  158. "-87.78418294588424,41.87145055520308,0 "
  159. "-87.7872369165933,41.8717239119163,0 "
  160. "-87.79160214925886,41.87210797280065,0"
  161. ),
  162. 1: (
  163. "-87.65758750947528,41.96427269188822,0 "
  164. "-87.65802133507393,41.96581929055245,0 "
  165. "-87.65819033925305,41.96621846093642,0 "
  166. "-87.6583189819129,41.96650362897086,0 "
  167. "-87.65835858701473,41.96669002089185,0 "
  168. "-87.65838428411853,41.96688150295095,0 "
  169. "-87.65842208882658,41.96745896091846,0 "
  170. "-87.65846556843937,41.9683761425439,0 "
  171. "-87.65849296214573,41.96913893870342,0"
  172. ),
  173. 2: (
  174. "-87.65492939166126,41.95377494531437,0 "
  175. "-87.65557043199591,41.95376544118533,0 "
  176. "-87.65606302030132,41.95376391658746,0 "
  177. "-87.65623502146268,41.95377379126367,0 "
  178. "-87.65634748981634,41.95380103566435,0 "
  179. "-87.65646537904269,41.95387703994676,0 "
  180. "-87.65656532461145,41.95396622645799,0 "
  181. "-87.65664760856414,41.95404201996044,0 "
  182. "-87.65671750555913,41.95416647054043,0 "
  183. "-87.65673983607117,41.95429949810849,0 "
  184. "-87.65673866475777,41.95441024240925,0 "
  185. "-87.6567690255541,41.95490657227902,0 "
  186. "-87.65683672482363,41.95692259283837,0 "
  187. "-87.6568900886376,41.95861070983142,0 "
  188. "-87.65699865558875,41.96181418669004,0 "
  189. "-87.65756347177603,41.96397045777844,0 "
  190. "-87.65758750947528,41.96427269188822,0"
  191. ),
  192. 3: (
  193. "-87.65362593118043,41.94742799535678,0 "
  194. "-87.65363554415794,41.94819886386848,0 "
  195. "-87.6536456393239,41.95059994675451,0 "
  196. "-87.65365831235026,41.95108288489359,0 "
  197. "-87.6536604873874,41.9519954657554,0 "
  198. "-87.65362592053201,41.95245597302328,0 "
  199. "-87.65367158496069,41.95311153649393,0 "
  200. "-87.65368468595476,41.9533202828916,0 "
  201. "-87.65369271253692,41.95343095587119,0 "
  202. "-87.65373335834569,41.95351536301472,0 "
  203. "-87.65378605844126,41.95358212680591,0 "
  204. "-87.65385067928185,41.95364452823767,0 "
  205. "-87.6539390793817,41.95370263886964,0 "
  206. "-87.6540786298351,41.95373403675265,0 "
  207. "-87.65430648647626,41.9537535411832,0 "
  208. "-87.65492939166126,41.95377494531437,0"
  209. ),
  210. 4: (
  211. "-87.65345391792157,41.94217681262115,0 "
  212. "-87.65342448305786,41.94237224420864,0 "
  213. "-87.65339745703922,41.94268217746244,0 "
  214. "-87.65337753982941,41.94288140770284,0 "
  215. "-87.65336256753105,41.94317369618263,0 "
  216. "-87.65338799707138,41.94357253961736,0 "
  217. "-87.65340240886648,41.94389158188269,0 "
  218. "-87.65341837392448,41.94406444407721,0 "
  219. "-87.65342275247338,41.94421065714904,0 "
  220. "-87.65347469646018,41.94434829382345,0 "
  221. "-87.65351486483024,41.94447699917548,0 "
  222. "-87.65353483605053,41.9453896864472,0 "
  223. "-87.65361975532807,41.94689193720703,0 "
  224. "-87.65362593118043,41.94742799535678,0"
  225. ),
  226. },
  227. }
  228. )
  229. def test_literal_xml_deprecation():
  230. # GH 53809
  231. pytest.importorskip("lxml")
  232. msg = (
  233. "Passing literal xml to 'read_xml' is deprecated and "
  234. "will be removed in a future version. To read from a "
  235. "literal string, wrap it in a 'StringIO' object."
  236. )
  237. with tm.assert_produces_warning(FutureWarning, match=msg):
  238. read_xml(xml_default_nmsp)
  239. @pytest.fixture(params=["rb", "r"])
  240. def mode(request):
  241. return request.param
  242. @pytest.fixture(params=[pytest.param("lxml", marks=td.skip_if_no("lxml")), "etree"])
  243. def parser(request):
  244. return request.param
  245. def read_xml_iterparse(data, **kwargs):
  246. with tm.ensure_clean() as path:
  247. with open(path, "w", encoding="utf-8") as f:
  248. f.write(data)
  249. return read_xml(path, **kwargs)
  250. def read_xml_iterparse_comp(comp_path, compression_only, **kwargs):
  251. with get_handle(comp_path, "r", compression=compression_only) as handles:
  252. with tm.ensure_clean() as path:
  253. with open(path, "w", encoding="utf-8") as f:
  254. f.write(handles.handle.read())
  255. return read_xml(path, **kwargs)
  256. # FILE / URL
  257. def test_parser_consistency_file(xml_books):
  258. pytest.importorskip("lxml")
  259. df_file_lxml = read_xml(xml_books, parser="lxml")
  260. df_file_etree = read_xml(xml_books, parser="etree")
  261. df_iter_lxml = read_xml(
  262. xml_books,
  263. parser="lxml",
  264. iterparse={"book": ["category", "title", "year", "author", "price"]},
  265. )
  266. df_iter_etree = read_xml(
  267. xml_books,
  268. parser="etree",
  269. iterparse={"book": ["category", "title", "year", "author", "price"]},
  270. )
  271. tm.assert_frame_equal(df_file_lxml, df_file_etree)
  272. tm.assert_frame_equal(df_file_lxml, df_iter_lxml)
  273. tm.assert_frame_equal(df_iter_lxml, df_iter_etree)
  274. @pytest.mark.network
  275. @pytest.mark.single_cpu
  276. def test_parser_consistency_url(parser, httpserver):
  277. httpserver.serve_content(content=xml_default_nmsp)
  278. df_xpath = read_xml(StringIO(xml_default_nmsp), parser=parser)
  279. df_iter = read_xml(
  280. BytesIO(xml_default_nmsp.encode()),
  281. parser=parser,
  282. iterparse={"row": ["shape", "degrees", "sides"]},
  283. )
  284. tm.assert_frame_equal(df_xpath, df_iter)
  285. def test_file_like(xml_books, parser, mode):
  286. with open(xml_books, mode, encoding="utf-8" if mode == "r" else None) as f:
  287. df_file = read_xml(f, parser=parser)
  288. df_expected = DataFrame(
  289. {
  290. "category": ["cooking", "children", "web"],
  291. "title": ["Everyday Italian", "Harry Potter", "Learning XML"],
  292. "author": ["Giada De Laurentiis", "J K. Rowling", "Erik T. Ray"],
  293. "year": [2005, 2005, 2003],
  294. "price": [30.00, 29.99, 39.95],
  295. }
  296. )
  297. tm.assert_frame_equal(df_file, df_expected)
  298. def test_file_io(xml_books, parser, mode):
  299. with open(xml_books, mode, encoding="utf-8" if mode == "r" else None) as f:
  300. xml_obj = f.read()
  301. df_io = read_xml(
  302. (BytesIO(xml_obj) if isinstance(xml_obj, bytes) else StringIO(xml_obj)),
  303. parser=parser,
  304. )
  305. df_expected = DataFrame(
  306. {
  307. "category": ["cooking", "children", "web"],
  308. "title": ["Everyday Italian", "Harry Potter", "Learning XML"],
  309. "author": ["Giada De Laurentiis", "J K. Rowling", "Erik T. Ray"],
  310. "year": [2005, 2005, 2003],
  311. "price": [30.00, 29.99, 39.95],
  312. }
  313. )
  314. tm.assert_frame_equal(df_io, df_expected)
  315. def test_file_buffered_reader_string(xml_books, parser, mode):
  316. with open(xml_books, mode, encoding="utf-8" if mode == "r" else None) as f:
  317. xml_obj = f.read()
  318. if mode == "rb":
  319. xml_obj = StringIO(xml_obj.decode())
  320. elif mode == "r":
  321. xml_obj = StringIO(xml_obj)
  322. df_str = read_xml(xml_obj, parser=parser)
  323. df_expected = DataFrame(
  324. {
  325. "category": ["cooking", "children", "web"],
  326. "title": ["Everyday Italian", "Harry Potter", "Learning XML"],
  327. "author": ["Giada De Laurentiis", "J K. Rowling", "Erik T. Ray"],
  328. "year": [2005, 2005, 2003],
  329. "price": [30.00, 29.99, 39.95],
  330. }
  331. )
  332. tm.assert_frame_equal(df_str, df_expected)
  333. def test_file_buffered_reader_no_xml_declaration(xml_books, parser, mode):
  334. with open(xml_books, mode, encoding="utf-8" if mode == "r" else None) as f:
  335. next(f)
  336. xml_obj = f.read()
  337. if mode == "rb":
  338. xml_obj = StringIO(xml_obj.decode())
  339. elif mode == "r":
  340. xml_obj = StringIO(xml_obj)
  341. df_str = read_xml(xml_obj, parser=parser)
  342. df_expected = DataFrame(
  343. {
  344. "category": ["cooking", "children", "web"],
  345. "title": ["Everyday Italian", "Harry Potter", "Learning XML"],
  346. "author": ["Giada De Laurentiis", "J K. Rowling", "Erik T. Ray"],
  347. "year": [2005, 2005, 2003],
  348. "price": [30.00, 29.99, 39.95],
  349. }
  350. )
  351. tm.assert_frame_equal(df_str, df_expected)
  352. def test_string_charset(parser):
  353. txt = "<中文標籤><row><c1>1</c1><c2>2</c2></row></中文標籤>"
  354. df_str = read_xml(StringIO(txt), parser=parser)
  355. df_expected = DataFrame({"c1": 1, "c2": 2}, index=[0])
  356. tm.assert_frame_equal(df_str, df_expected)
  357. def test_file_charset(xml_doc_ch_utf, parser):
  358. df_file = read_xml(xml_doc_ch_utf, parser=parser)
  359. df_expected = DataFrame(
  360. {
  361. "問": [
  362. "問 若箇是邪而言破邪 何者是正而道(Sorry, this is Big5 only)申正",
  363. "問 既破有得申無得 亦應但破性執申假名以不",
  364. "問 既破性申假 亦應但破有申無 若有無兩洗 亦應性假雙破耶",
  365. ],
  366. "答": [
  367. "".join(
  368. [
  369. "答 邪既無量 正亦多途 大略為言不出二種 謂",
  370. "有得與無得 有得是邪須破 無得是正須申\n\t\t故",
  371. ]
  372. ),
  373. None,
  374. "答 不例 有無皆是性 所以須雙破 既分性假異 故有破不破",
  375. ],
  376. "a": [
  377. None,
  378. "答 性執是有得 假名是無得 今破有得申無得 即是破性執申假名也",
  379. None,
  380. ],
  381. }
  382. )
  383. tm.assert_frame_equal(df_file, df_expected)
  384. def test_file_handle_close(xml_books, parser):
  385. with open(xml_books, "rb") as f:
  386. read_xml(BytesIO(f.read()), parser=parser)
  387. assert not f.closed
  388. @pytest.mark.parametrize("val", ["", b""])
  389. def test_empty_string_lxml(val):
  390. lxml_etree = pytest.importorskip("lxml.etree")
  391. msg = "|".join(
  392. [
  393. "Document is empty",
  394. # Seen on Mac with lxml 4.91
  395. r"None \(line 0\)",
  396. ]
  397. )
  398. with pytest.raises(lxml_etree.XMLSyntaxError, match=msg):
  399. if isinstance(val, str):
  400. read_xml(StringIO(val), parser="lxml")
  401. else:
  402. read_xml(BytesIO(val), parser="lxml")
  403. @pytest.mark.parametrize("val", ["", b""])
  404. def test_empty_string_etree(val):
  405. with pytest.raises(ParseError, match="no element found"):
  406. if isinstance(val, str):
  407. read_xml(StringIO(val), parser="etree")
  408. else:
  409. read_xml(BytesIO(val), parser="etree")
  410. def test_wrong_file_path(parser):
  411. msg = (
  412. "Passing literal xml to 'read_xml' is deprecated and "
  413. "will be removed in a future version. To read from a "
  414. "literal string, wrap it in a 'StringIO' object."
  415. )
  416. filename = os.path.join("data", "html", "books.xml")
  417. with pytest.raises(
  418. FutureWarning,
  419. match=msg,
  420. ):
  421. read_xml(filename, parser=parser)
  422. @pytest.mark.network
  423. @pytest.mark.single_cpu
  424. def test_url(httpserver, xml_file):
  425. pytest.importorskip("lxml")
  426. with open(xml_file, encoding="utf-8") as f:
  427. httpserver.serve_content(content=f.read())
  428. df_url = read_xml(httpserver.url, xpath=".//book[count(*)=4]")
  429. df_expected = DataFrame(
  430. {
  431. "category": ["cooking", "children", "web"],
  432. "title": ["Everyday Italian", "Harry Potter", "Learning XML"],
  433. "author": ["Giada De Laurentiis", "J K. Rowling", "Erik T. Ray"],
  434. "year": [2005, 2005, 2003],
  435. "price": [30.00, 29.99, 39.95],
  436. }
  437. )
  438. tm.assert_frame_equal(df_url, df_expected)
  439. @pytest.mark.network
  440. @pytest.mark.single_cpu
  441. def test_wrong_url(parser, httpserver):
  442. httpserver.serve_content("NOT FOUND", code=404)
  443. with pytest.raises(HTTPError, match=("HTTP Error 404: NOT FOUND")):
  444. read_xml(httpserver.url, xpath=".//book[count(*)=4]", parser=parser)
  445. # CONTENT
  446. def test_whitespace(parser):
  447. xml = """
  448. <data>
  449. <row sides=" 4 ">
  450. <shape>
  451. square
  452. </shape>
  453. <degrees>&#009;360&#009;</degrees>
  454. </row>
  455. <row sides=" 0 ">
  456. <shape>
  457. circle
  458. </shape>
  459. <degrees>&#009;360&#009;</degrees>
  460. </row>
  461. <row sides=" 3 ">
  462. <shape>
  463. triangle
  464. </shape>
  465. <degrees>&#009;180&#009;</degrees>
  466. </row>
  467. </data>"""
  468. df_xpath = read_xml(StringIO(xml), parser=parser, dtype="string")
  469. df_iter = read_xml_iterparse(
  470. xml,
  471. parser=parser,
  472. iterparse={"row": ["sides", "shape", "degrees"]},
  473. dtype="string",
  474. )
  475. df_expected = DataFrame(
  476. {
  477. "sides": [" 4 ", " 0 ", " 3 "],
  478. "shape": [
  479. "\n square\n ",
  480. "\n circle\n ",
  481. "\n triangle\n ",
  482. ],
  483. "degrees": ["\t360\t", "\t360\t", "\t180\t"],
  484. },
  485. dtype="string",
  486. )
  487. tm.assert_frame_equal(df_xpath, df_expected)
  488. tm.assert_frame_equal(df_iter, df_expected)
  489. # XPATH
  490. def test_empty_xpath_lxml(xml_books):
  491. pytest.importorskip("lxml")
  492. with pytest.raises(ValueError, match=("xpath does not return any nodes")):
  493. read_xml(xml_books, xpath=".//python", parser="lxml")
  494. def test_bad_xpath_etree(xml_books):
  495. with pytest.raises(
  496. SyntaxError, match=("You have used an incorrect or unsupported XPath")
  497. ):
  498. read_xml(xml_books, xpath=".//[book]", parser="etree")
  499. def test_bad_xpath_lxml(xml_books):
  500. lxml_etree = pytest.importorskip("lxml.etree")
  501. with pytest.raises(lxml_etree.XPathEvalError, match=("Invalid expression")):
  502. read_xml(xml_books, xpath=".//[book]", parser="lxml")
  503. # NAMESPACE
  504. def test_default_namespace(parser):
  505. df_nmsp = read_xml(
  506. StringIO(xml_default_nmsp),
  507. xpath=".//ns:row",
  508. namespaces={"ns": "http://example.com"},
  509. parser=parser,
  510. )
  511. df_iter = read_xml_iterparse(
  512. xml_default_nmsp,
  513. parser=parser,
  514. iterparse={"row": ["shape", "degrees", "sides"]},
  515. )
  516. df_expected = DataFrame(
  517. {
  518. "shape": ["square", "circle", "triangle"],
  519. "degrees": [360, 360, 180],
  520. "sides": [4.0, float("nan"), 3.0],
  521. }
  522. )
  523. tm.assert_frame_equal(df_nmsp, df_expected)
  524. tm.assert_frame_equal(df_iter, df_expected)
  525. def test_prefix_namespace(parser):
  526. df_nmsp = read_xml(
  527. StringIO(xml_prefix_nmsp),
  528. xpath=".//doc:row",
  529. namespaces={"doc": "http://example.com"},
  530. parser=parser,
  531. )
  532. df_iter = read_xml_iterparse(
  533. xml_prefix_nmsp, parser=parser, iterparse={"row": ["shape", "degrees", "sides"]}
  534. )
  535. df_expected = DataFrame(
  536. {
  537. "shape": ["square", "circle", "triangle"],
  538. "degrees": [360, 360, 180],
  539. "sides": [4.0, float("nan"), 3.0],
  540. }
  541. )
  542. tm.assert_frame_equal(df_nmsp, df_expected)
  543. tm.assert_frame_equal(df_iter, df_expected)
  544. def test_consistency_default_namespace():
  545. pytest.importorskip("lxml")
  546. df_lxml = read_xml(
  547. StringIO(xml_default_nmsp),
  548. xpath=".//ns:row",
  549. namespaces={"ns": "http://example.com"},
  550. parser="lxml",
  551. )
  552. df_etree = read_xml(
  553. StringIO(xml_default_nmsp),
  554. xpath=".//doc:row",
  555. namespaces={"doc": "http://example.com"},
  556. parser="etree",
  557. )
  558. tm.assert_frame_equal(df_lxml, df_etree)
  559. def test_consistency_prefix_namespace():
  560. pytest.importorskip("lxml")
  561. df_lxml = read_xml(
  562. StringIO(xml_prefix_nmsp),
  563. xpath=".//doc:row",
  564. namespaces={"doc": "http://example.com"},
  565. parser="lxml",
  566. )
  567. df_etree = read_xml(
  568. StringIO(xml_prefix_nmsp),
  569. xpath=".//doc:row",
  570. namespaces={"doc": "http://example.com"},
  571. parser="etree",
  572. )
  573. tm.assert_frame_equal(df_lxml, df_etree)
  574. # PREFIX
  575. def test_missing_prefix_with_default_namespace(xml_books, parser):
  576. with pytest.raises(ValueError, match=("xpath does not return any nodes")):
  577. read_xml(xml_books, xpath=".//Placemark", parser=parser)
  578. def test_missing_prefix_definition_etree(kml_cta_rail_lines):
  579. with pytest.raises(SyntaxError, match=("you used an undeclared namespace prefix")):
  580. read_xml(kml_cta_rail_lines, xpath=".//kml:Placemark", parser="etree")
  581. def test_missing_prefix_definition_lxml(kml_cta_rail_lines):
  582. lxml_etree = pytest.importorskip("lxml.etree")
  583. with pytest.raises(lxml_etree.XPathEvalError, match=("Undefined namespace prefix")):
  584. read_xml(kml_cta_rail_lines, xpath=".//kml:Placemark", parser="lxml")
  585. @pytest.mark.parametrize("key", ["", None])
  586. def test_none_namespace_prefix(key):
  587. pytest.importorskip("lxml")
  588. with pytest.raises(
  589. TypeError, match=("empty namespace prefix is not supported in XPath")
  590. ):
  591. read_xml(
  592. StringIO(xml_default_nmsp),
  593. xpath=".//kml:Placemark",
  594. namespaces={key: "http://www.opengis.net/kml/2.2"},
  595. parser="lxml",
  596. )
  597. # ELEMS AND ATTRS
  598. def test_file_elems_and_attrs(xml_books, parser):
  599. df_file = read_xml(xml_books, parser=parser)
  600. df_iter = read_xml(
  601. xml_books,
  602. parser=parser,
  603. iterparse={"book": ["category", "title", "author", "year", "price"]},
  604. )
  605. df_expected = DataFrame(
  606. {
  607. "category": ["cooking", "children", "web"],
  608. "title": ["Everyday Italian", "Harry Potter", "Learning XML"],
  609. "author": ["Giada De Laurentiis", "J K. Rowling", "Erik T. Ray"],
  610. "year": [2005, 2005, 2003],
  611. "price": [30.00, 29.99, 39.95],
  612. }
  613. )
  614. tm.assert_frame_equal(df_file, df_expected)
  615. tm.assert_frame_equal(df_iter, df_expected)
  616. def test_file_only_attrs(xml_books, parser):
  617. df_file = read_xml(xml_books, attrs_only=True, parser=parser)
  618. df_iter = read_xml(xml_books, parser=parser, iterparse={"book": ["category"]})
  619. df_expected = DataFrame({"category": ["cooking", "children", "web"]})
  620. tm.assert_frame_equal(df_file, df_expected)
  621. tm.assert_frame_equal(df_iter, df_expected)
  622. def test_file_only_elems(xml_books, parser):
  623. df_file = read_xml(xml_books, elems_only=True, parser=parser)
  624. df_iter = read_xml(
  625. xml_books,
  626. parser=parser,
  627. iterparse={"book": ["title", "author", "year", "price"]},
  628. )
  629. df_expected = DataFrame(
  630. {
  631. "title": ["Everyday Italian", "Harry Potter", "Learning XML"],
  632. "author": ["Giada De Laurentiis", "J K. Rowling", "Erik T. Ray"],
  633. "year": [2005, 2005, 2003],
  634. "price": [30.00, 29.99, 39.95],
  635. }
  636. )
  637. tm.assert_frame_equal(df_file, df_expected)
  638. tm.assert_frame_equal(df_iter, df_expected)
  639. def test_elem_and_attrs_only(kml_cta_rail_lines, parser):
  640. with pytest.raises(
  641. ValueError,
  642. match=("Either element or attributes can be parsed not both"),
  643. ):
  644. read_xml(kml_cta_rail_lines, elems_only=True, attrs_only=True, parser=parser)
  645. def test_empty_attrs_only(parser):
  646. xml = """
  647. <data>
  648. <row>
  649. <shape sides="4">square</shape>
  650. <degrees>360</degrees>
  651. </row>
  652. <row>
  653. <shape sides="0">circle</shape>
  654. <degrees>360</degrees>
  655. </row>
  656. <row>
  657. <shape sides="3">triangle</shape>
  658. <degrees>180</degrees>
  659. </row>
  660. </data>"""
  661. with pytest.raises(
  662. ValueError,
  663. match=("xpath does not return any nodes or attributes"),
  664. ):
  665. read_xml(StringIO(xml), xpath="./row", attrs_only=True, parser=parser)
  666. def test_empty_elems_only(parser):
  667. xml = """
  668. <data>
  669. <row sides="4" shape="square" degrees="360"/>
  670. <row sides="0" shape="circle" degrees="360"/>
  671. <row sides="3" shape="triangle" degrees="180"/>
  672. </data>"""
  673. with pytest.raises(
  674. ValueError,
  675. match=("xpath does not return any nodes or attributes"),
  676. ):
  677. read_xml(StringIO(xml), xpath="./row", elems_only=True, parser=parser)
  678. def test_attribute_centric_xml():
  679. pytest.importorskip("lxml")
  680. xml = """\
  681. <?xml version="1.0" encoding="UTF-8"?>
  682. <TrainSchedule>
  683. <Stations>
  684. <station Name="Manhattan" coords="31,460,195,498"/>
  685. <station Name="Laraway Road" coords="63,409,194,455"/>
  686. <station Name="179th St (Orland Park)" coords="0,364,110,395"/>
  687. <station Name="153rd St (Orland Park)" coords="7,333,113,362"/>
  688. <station Name="143rd St (Orland Park)" coords="17,297,115,330"/>
  689. <station Name="Palos Park" coords="128,281,239,303"/>
  690. <station Name="Palos Heights" coords="148,257,283,279"/>
  691. <station Name="Worth" coords="170,230,248,255"/>
  692. <station Name="Chicago Ridge" coords="70,187,208,214"/>
  693. <station Name="Oak Lawn" coords="166,159,266,185"/>
  694. <station Name="Ashburn" coords="197,133,336,157"/>
  695. <station Name="Wrightwood" coords="219,106,340,133"/>
  696. <station Name="Chicago Union Sta" coords="220,0,360,43"/>
  697. </Stations>
  698. </TrainSchedule>"""
  699. df_lxml = read_xml(StringIO(xml), xpath=".//station")
  700. df_etree = read_xml(StringIO(xml), xpath=".//station", parser="etree")
  701. df_iter_lx = read_xml_iterparse(xml, iterparse={"station": ["Name", "coords"]})
  702. df_iter_et = read_xml_iterparse(
  703. xml, parser="etree", iterparse={"station": ["Name", "coords"]}
  704. )
  705. tm.assert_frame_equal(df_lxml, df_etree)
  706. tm.assert_frame_equal(df_iter_lx, df_iter_et)
  707. # NAMES
  708. def test_names_option_output(xml_books, parser):
  709. df_file = read_xml(
  710. xml_books, names=["Col1", "Col2", "Col3", "Col4", "Col5"], parser=parser
  711. )
  712. df_iter = read_xml(
  713. xml_books,
  714. parser=parser,
  715. names=["Col1", "Col2", "Col3", "Col4", "Col5"],
  716. iterparse={"book": ["category", "title", "author", "year", "price"]},
  717. )
  718. df_expected = DataFrame(
  719. {
  720. "Col1": ["cooking", "children", "web"],
  721. "Col2": ["Everyday Italian", "Harry Potter", "Learning XML"],
  722. "Col3": ["Giada De Laurentiis", "J K. Rowling", "Erik T. Ray"],
  723. "Col4": [2005, 2005, 2003],
  724. "Col5": [30.00, 29.99, 39.95],
  725. }
  726. )
  727. tm.assert_frame_equal(df_file, df_expected)
  728. tm.assert_frame_equal(df_iter, df_expected)
  729. def test_repeat_names(parser):
  730. xml = """\
  731. <shapes>
  732. <shape type="2D">
  733. <name>circle</name>
  734. <type>curved</type>
  735. </shape>
  736. <shape type="3D">
  737. <name>sphere</name>
  738. <type>curved</type>
  739. </shape>
  740. </shapes>"""
  741. df_xpath = read_xml(
  742. StringIO(xml),
  743. xpath=".//shape",
  744. parser=parser,
  745. names=["type_dim", "shape", "type_edge"],
  746. )
  747. df_iter = read_xml_iterparse(
  748. xml,
  749. parser=parser,
  750. iterparse={"shape": ["type", "name", "type"]},
  751. names=["type_dim", "shape", "type_edge"],
  752. )
  753. df_expected = DataFrame(
  754. {
  755. "type_dim": ["2D", "3D"],
  756. "shape": ["circle", "sphere"],
  757. "type_edge": ["curved", "curved"],
  758. }
  759. )
  760. tm.assert_frame_equal(df_xpath, df_expected)
  761. tm.assert_frame_equal(df_iter, df_expected)
  762. def test_repeat_values_new_names(parser):
  763. xml = """\
  764. <shapes>
  765. <shape>
  766. <name>rectangle</name>
  767. <family>rectangle</family>
  768. </shape>
  769. <shape>
  770. <name>square</name>
  771. <family>rectangle</family>
  772. </shape>
  773. <shape>
  774. <name>ellipse</name>
  775. <family>ellipse</family>
  776. </shape>
  777. <shape>
  778. <name>circle</name>
  779. <family>ellipse</family>
  780. </shape>
  781. </shapes>"""
  782. df_xpath = read_xml(
  783. StringIO(xml), xpath=".//shape", parser=parser, names=["name", "group"]
  784. )
  785. df_iter = read_xml_iterparse(
  786. xml,
  787. parser=parser,
  788. iterparse={"shape": ["name", "family"]},
  789. names=["name", "group"],
  790. )
  791. df_expected = DataFrame(
  792. {
  793. "name": ["rectangle", "square", "ellipse", "circle"],
  794. "group": ["rectangle", "rectangle", "ellipse", "ellipse"],
  795. }
  796. )
  797. tm.assert_frame_equal(df_xpath, df_expected)
  798. tm.assert_frame_equal(df_iter, df_expected)
  799. def test_repeat_elements(parser):
  800. xml = """\
  801. <shapes>
  802. <shape>
  803. <value item="name">circle</value>
  804. <value item="family">ellipse</value>
  805. <value item="degrees">360</value>
  806. <value item="sides">0</value>
  807. </shape>
  808. <shape>
  809. <value item="name">triangle</value>
  810. <value item="family">polygon</value>
  811. <value item="degrees">180</value>
  812. <value item="sides">3</value>
  813. </shape>
  814. <shape>
  815. <value item="name">square</value>
  816. <value item="family">polygon</value>
  817. <value item="degrees">360</value>
  818. <value item="sides">4</value>
  819. </shape>
  820. </shapes>"""
  821. df_xpath = read_xml(
  822. StringIO(xml),
  823. xpath=".//shape",
  824. parser=parser,
  825. names=["name", "family", "degrees", "sides"],
  826. )
  827. df_iter = read_xml_iterparse(
  828. xml,
  829. parser=parser,
  830. iterparse={"shape": ["value", "value", "value", "value"]},
  831. names=["name", "family", "degrees", "sides"],
  832. )
  833. df_expected = DataFrame(
  834. {
  835. "name": ["circle", "triangle", "square"],
  836. "family": ["ellipse", "polygon", "polygon"],
  837. "degrees": [360, 180, 360],
  838. "sides": [0, 3, 4],
  839. }
  840. )
  841. tm.assert_frame_equal(df_xpath, df_expected)
  842. tm.assert_frame_equal(df_iter, df_expected)
  843. def test_names_option_wrong_length(xml_books, parser):
  844. with pytest.raises(ValueError, match=("names does not match length")):
  845. read_xml(xml_books, names=["Col1", "Col2", "Col3"], parser=parser)
  846. def test_names_option_wrong_type(xml_books, parser):
  847. with pytest.raises(TypeError, match=("is not a valid type for names")):
  848. read_xml(xml_books, names="Col1, Col2, Col3", parser=parser)
  849. # ENCODING
  850. def test_wrong_encoding(xml_baby_names, parser):
  851. with pytest.raises(UnicodeDecodeError, match=("'utf-8' codec can't decode")):
  852. read_xml(xml_baby_names, parser=parser)
  853. def test_utf16_encoding(xml_baby_names, parser):
  854. with pytest.raises(
  855. UnicodeError,
  856. match=(
  857. "UTF-16 stream does not start with BOM|"
  858. "'utf-16(-le)?' codec can't decode byte"
  859. ),
  860. ):
  861. read_xml(xml_baby_names, encoding="UTF-16", parser=parser)
  862. def test_unknown_encoding(xml_baby_names, parser):
  863. with pytest.raises(LookupError, match=("unknown encoding: UFT-8")):
  864. read_xml(xml_baby_names, encoding="UFT-8", parser=parser)
  865. def test_ascii_encoding(xml_baby_names, parser):
  866. with pytest.raises(UnicodeDecodeError, match=("'ascii' codec can't decode byte")):
  867. read_xml(xml_baby_names, encoding="ascii", parser=parser)
  868. def test_parser_consistency_with_encoding(xml_baby_names):
  869. pytest.importorskip("lxml")
  870. df_xpath_lxml = read_xml(xml_baby_names, parser="lxml", encoding="ISO-8859-1")
  871. df_xpath_etree = read_xml(xml_baby_names, parser="etree", encoding="iso-8859-1")
  872. df_iter_lxml = read_xml(
  873. xml_baby_names,
  874. parser="lxml",
  875. encoding="ISO-8859-1",
  876. iterparse={"row": ["rank", "malename", "femalename"]},
  877. )
  878. df_iter_etree = read_xml(
  879. xml_baby_names,
  880. parser="etree",
  881. encoding="ISO-8859-1",
  882. iterparse={"row": ["rank", "malename", "femalename"]},
  883. )
  884. tm.assert_frame_equal(df_xpath_lxml, df_xpath_etree)
  885. tm.assert_frame_equal(df_xpath_etree, df_iter_etree)
  886. tm.assert_frame_equal(df_iter_lxml, df_iter_etree)
  887. def test_wrong_encoding_for_lxml():
  888. pytest.importorskip("lxml")
  889. # GH#45133
  890. data = """<data>
  891. <row>
  892. <a>c</a>
  893. </row>
  894. </data>
  895. """
  896. with pytest.raises(TypeError, match="encoding None"):
  897. read_xml(StringIO(data), parser="lxml", encoding=None)
  898. def test_none_encoding_etree():
  899. # GH#45133
  900. data = """<data>
  901. <row>
  902. <a>c</a>
  903. </row>
  904. </data>
  905. """
  906. result = read_xml(StringIO(data), parser="etree", encoding=None)
  907. expected = DataFrame({"a": ["c"]})
  908. tm.assert_frame_equal(result, expected)
  909. # PARSER
  910. @td.skip_if_installed("lxml")
  911. def test_default_parser_no_lxml(xml_books):
  912. with pytest.raises(
  913. ImportError, match=("lxml not found, please install or use the etree parser.")
  914. ):
  915. read_xml(xml_books)
  916. def test_wrong_parser(xml_books):
  917. with pytest.raises(
  918. ValueError, match=("Values for parser can only be lxml or etree.")
  919. ):
  920. read_xml(xml_books, parser="bs4")
  921. # STYLESHEET
  922. def test_stylesheet_file(kml_cta_rail_lines, xsl_flatten_doc):
  923. pytest.importorskip("lxml")
  924. df_style = read_xml(
  925. kml_cta_rail_lines,
  926. xpath=".//k:Placemark",
  927. namespaces={"k": "http://www.opengis.net/kml/2.2"},
  928. stylesheet=xsl_flatten_doc,
  929. )
  930. df_iter = read_xml(
  931. kml_cta_rail_lines,
  932. iterparse={
  933. "Placemark": [
  934. "id",
  935. "name",
  936. "styleUrl",
  937. "extrude",
  938. "altitudeMode",
  939. "coordinates",
  940. ]
  941. },
  942. )
  943. tm.assert_frame_equal(df_kml, df_style)
  944. tm.assert_frame_equal(df_kml, df_iter)
  945. def test_stylesheet_file_like(kml_cta_rail_lines, xsl_flatten_doc, mode):
  946. pytest.importorskip("lxml")
  947. with open(xsl_flatten_doc, mode, encoding="utf-8" if mode == "r" else None) as f:
  948. df_style = read_xml(
  949. kml_cta_rail_lines,
  950. xpath=".//k:Placemark",
  951. namespaces={"k": "http://www.opengis.net/kml/2.2"},
  952. stylesheet=f,
  953. )
  954. tm.assert_frame_equal(df_kml, df_style)
  955. def test_stylesheet_io(kml_cta_rail_lines, xsl_flatten_doc, mode):
  956. # note: By default the bodies of untyped functions are not checked,
  957. # consider using --check-untyped-defs
  958. pytest.importorskip("lxml")
  959. xsl_obj: BytesIO | StringIO # type: ignore[annotation-unchecked]
  960. with open(xsl_flatten_doc, mode, encoding="utf-8" if mode == "r" else None) as f:
  961. if mode == "rb":
  962. xsl_obj = BytesIO(f.read())
  963. else:
  964. xsl_obj = StringIO(f.read())
  965. df_style = read_xml(
  966. kml_cta_rail_lines,
  967. xpath=".//k:Placemark",
  968. namespaces={"k": "http://www.opengis.net/kml/2.2"},
  969. stylesheet=xsl_obj,
  970. )
  971. tm.assert_frame_equal(df_kml, df_style)
  972. def test_stylesheet_buffered_reader(kml_cta_rail_lines, xsl_flatten_doc, mode):
  973. pytest.importorskip("lxml")
  974. with open(xsl_flatten_doc, mode, encoding="utf-8" if mode == "r" else None) as f:
  975. xsl_obj = f.read()
  976. df_style = read_xml(
  977. kml_cta_rail_lines,
  978. xpath=".//k:Placemark",
  979. namespaces={"k": "http://www.opengis.net/kml/2.2"},
  980. stylesheet=xsl_obj,
  981. )
  982. tm.assert_frame_equal(df_kml, df_style)
  983. def test_style_charset():
  984. pytest.importorskip("lxml")
  985. xml = "<中文標籤><row><c1>1</c1><c2>2</c2></row></中文標籤>"
  986. xsl = """\
  987. <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  988. <xsl:output omit-xml-declaration="yes" indent="yes"/>
  989. <xsl:strip-space elements="*"/>
  990. <xsl:template match="node()|@*">
  991. <xsl:copy>
  992. <xsl:apply-templates select="node()|@*"/>
  993. </xsl:copy>
  994. </xsl:template>
  995. <xsl:template match="中文標籤">
  996. <根>
  997. <xsl:apply-templates />
  998. </根>
  999. </xsl:template>
  1000. </xsl:stylesheet>"""
  1001. df_orig = read_xml(StringIO(xml))
  1002. df_style = read_xml(StringIO(xml), stylesheet=xsl)
  1003. tm.assert_frame_equal(df_orig, df_style)
  1004. def test_not_stylesheet(kml_cta_rail_lines, xml_books):
  1005. lxml_etree = pytest.importorskip("lxml.etree")
  1006. with pytest.raises(
  1007. lxml_etree.XSLTParseError, match=("document is not a stylesheet")
  1008. ):
  1009. read_xml(kml_cta_rail_lines, stylesheet=xml_books)
  1010. def test_incorrect_xsl_syntax(kml_cta_rail_lines):
  1011. lxml_etree = pytest.importorskip("lxml.etree")
  1012. xsl = """\
  1013. <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  1014. xmlns:k="http://www.opengis.net/kml/2.2"/>
  1015. <xsl:output method="xml" omit-xml-declaration="yes"
  1016. cdata-section-elements="k:description" indent="yes"/>
  1017. <xsl:strip-space elements="*"/>
  1018. <xsl:template match="node()|@*">
  1019. <xsl:copy>
  1020. <xsl:apply-templates select="node()|@*"/>
  1021. </xsl:copy>
  1022. </xsl:template>
  1023. <xsl:template match="k:MultiGeometry|k:LineString">
  1024. <xsl:apply-templates select='*'/>
  1025. </xsl:template>
  1026. <xsl:template match="k:description|k:Snippet|k:Style"/>
  1027. </xsl:stylesheet>"""
  1028. with pytest.raises(
  1029. lxml_etree.XMLSyntaxError, match=("Extra content at the end of the document")
  1030. ):
  1031. read_xml(kml_cta_rail_lines, stylesheet=xsl)
  1032. def test_incorrect_xsl_eval(kml_cta_rail_lines):
  1033. lxml_etree = pytest.importorskip("lxml.etree")
  1034. xsl = """\
  1035. <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  1036. xmlns:k="http://www.opengis.net/kml/2.2">
  1037. <xsl:output method="xml" omit-xml-declaration="yes"
  1038. cdata-section-elements="k:description" indent="yes"/>
  1039. <xsl:strip-space elements="*"/>
  1040. <xsl:template match="node(*)|@*">
  1041. <xsl:copy>
  1042. <xsl:apply-templates select="node()|@*"/>
  1043. </xsl:copy>
  1044. </xsl:template>
  1045. <xsl:template match="k:MultiGeometry|k:LineString">
  1046. <xsl:apply-templates select='*'/>
  1047. </xsl:template>
  1048. <xsl:template match="k:description|k:Snippet|k:Style"/>
  1049. </xsl:stylesheet>"""
  1050. with pytest.raises(lxml_etree.XSLTParseError, match=("failed to compile")):
  1051. read_xml(kml_cta_rail_lines, stylesheet=xsl)
  1052. def test_incorrect_xsl_apply(kml_cta_rail_lines):
  1053. lxml_etree = pytest.importorskip("lxml.etree")
  1054. xsl = """\
  1055. <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  1056. <xsl:output method="xml" encoding="utf-8" indent="yes" />
  1057. <xsl:strip-space elements="*"/>
  1058. <xsl:template match="@*|node()">
  1059. <xsl:copy>
  1060. <xsl:copy-of select="document('non_existent.xml')/*"/>
  1061. </xsl:copy>
  1062. </xsl:template>
  1063. </xsl:stylesheet>"""
  1064. with pytest.raises(lxml_etree.XSLTApplyError, match=("Cannot resolve URI")):
  1065. read_xml(kml_cta_rail_lines, stylesheet=xsl)
  1066. def test_wrong_stylesheet(kml_cta_rail_lines, xml_data_path):
  1067. xml_etree = pytest.importorskip("lxml.etree")
  1068. xsl = xml_data_path / "flatten.xsl"
  1069. with pytest.raises(
  1070. xml_etree.XMLSyntaxError,
  1071. match=("Start tag expected, '<' not found"),
  1072. ):
  1073. read_xml(kml_cta_rail_lines, stylesheet=xsl)
  1074. def test_stylesheet_file_close(kml_cta_rail_lines, xsl_flatten_doc, mode):
  1075. # note: By default the bodies of untyped functions are not checked,
  1076. # consider using --check-untyped-defs
  1077. pytest.importorskip("lxml")
  1078. xsl_obj: BytesIO | StringIO # type: ignore[annotation-unchecked]
  1079. with open(xsl_flatten_doc, mode, encoding="utf-8" if mode == "r" else None) as f:
  1080. if mode == "rb":
  1081. xsl_obj = BytesIO(f.read())
  1082. else:
  1083. xsl_obj = StringIO(f.read())
  1084. read_xml(kml_cta_rail_lines, stylesheet=xsl_obj)
  1085. assert not f.closed
  1086. def test_stylesheet_with_etree(kml_cta_rail_lines, xsl_flatten_doc):
  1087. pytest.importorskip("lxml")
  1088. with pytest.raises(
  1089. ValueError, match=("To use stylesheet, you need lxml installed")
  1090. ):
  1091. read_xml(kml_cta_rail_lines, parser="etree", stylesheet=xsl_flatten_doc)
  1092. @pytest.mark.parametrize("val", ["", b""])
  1093. def test_empty_stylesheet(val):
  1094. pytest.importorskip("lxml")
  1095. msg = (
  1096. "Passing literal xml to 'read_xml' is deprecated and "
  1097. "will be removed in a future version. To read from a "
  1098. "literal string, wrap it in a 'StringIO' object."
  1099. )
  1100. kml = os.path.join("data", "xml", "cta_rail_lines.kml")
  1101. with pytest.raises(FutureWarning, match=msg):
  1102. read_xml(kml, stylesheet=val)
  1103. # ITERPARSE
  1104. def test_file_like_iterparse(xml_books, parser, mode):
  1105. with open(xml_books, mode, encoding="utf-8" if mode == "r" else None) as f:
  1106. if mode == "r" and parser == "lxml":
  1107. with pytest.raises(
  1108. TypeError, match=("reading file objects must return bytes objects")
  1109. ):
  1110. read_xml(
  1111. f,
  1112. parser=parser,
  1113. iterparse={
  1114. "book": ["category", "title", "year", "author", "price"]
  1115. },
  1116. )
  1117. return None
  1118. else:
  1119. df_filelike = read_xml(
  1120. f,
  1121. parser=parser,
  1122. iterparse={"book": ["category", "title", "year", "author", "price"]},
  1123. )
  1124. df_expected = DataFrame(
  1125. {
  1126. "category": ["cooking", "children", "web"],
  1127. "title": ["Everyday Italian", "Harry Potter", "Learning XML"],
  1128. "author": ["Giada De Laurentiis", "J K. Rowling", "Erik T. Ray"],
  1129. "year": [2005, 2005, 2003],
  1130. "price": [30.00, 29.99, 39.95],
  1131. }
  1132. )
  1133. tm.assert_frame_equal(df_filelike, df_expected)
  1134. def test_file_io_iterparse(xml_books, parser, mode):
  1135. funcIO = StringIO if mode == "r" else BytesIO
  1136. with open(
  1137. xml_books,
  1138. mode,
  1139. encoding="utf-8" if mode == "r" else None,
  1140. ) as f:
  1141. with funcIO(f.read()) as b:
  1142. if mode == "r" and parser == "lxml":
  1143. with pytest.raises(
  1144. TypeError, match=("reading file objects must return bytes objects")
  1145. ):
  1146. read_xml(
  1147. b,
  1148. parser=parser,
  1149. iterparse={
  1150. "book": ["category", "title", "year", "author", "price"]
  1151. },
  1152. )
  1153. return None
  1154. else:
  1155. df_fileio = read_xml(
  1156. b,
  1157. parser=parser,
  1158. iterparse={
  1159. "book": ["category", "title", "year", "author", "price"]
  1160. },
  1161. )
  1162. df_expected = DataFrame(
  1163. {
  1164. "category": ["cooking", "children", "web"],
  1165. "title": ["Everyday Italian", "Harry Potter", "Learning XML"],
  1166. "author": ["Giada De Laurentiis", "J K. Rowling", "Erik T. Ray"],
  1167. "year": [2005, 2005, 2003],
  1168. "price": [30.00, 29.99, 39.95],
  1169. }
  1170. )
  1171. tm.assert_frame_equal(df_fileio, df_expected)
  1172. @pytest.mark.network
  1173. @pytest.mark.single_cpu
  1174. def test_url_path_error(parser, httpserver, xml_file):
  1175. with open(xml_file, encoding="utf-8") as f:
  1176. httpserver.serve_content(content=f.read())
  1177. with pytest.raises(
  1178. ParserError, match=("iterparse is designed for large XML files")
  1179. ):
  1180. read_xml(
  1181. httpserver.url,
  1182. parser=parser,
  1183. iterparse={"row": ["shape", "degrees", "sides", "date"]},
  1184. )
  1185. def test_compression_error(parser, compression_only):
  1186. with tm.ensure_clean(filename="geom_xml.zip") as path:
  1187. geom_df.to_xml(path, parser=parser, compression=compression_only)
  1188. with pytest.raises(
  1189. ParserError, match=("iterparse is designed for large XML files")
  1190. ):
  1191. read_xml(
  1192. path,
  1193. parser=parser,
  1194. iterparse={"row": ["shape", "degrees", "sides", "date"]},
  1195. compression=compression_only,
  1196. )
  1197. def test_wrong_dict_type(xml_books, parser):
  1198. with pytest.raises(TypeError, match="list is not a valid type for iterparse"):
  1199. read_xml(
  1200. xml_books,
  1201. parser=parser,
  1202. iterparse=["category", "title", "year", "author", "price"],
  1203. )
  1204. def test_wrong_dict_value(xml_books, parser):
  1205. with pytest.raises(
  1206. TypeError, match="<class 'str'> is not a valid type for value in iterparse"
  1207. ):
  1208. read_xml(xml_books, parser=parser, iterparse={"book": "category"})
  1209. def test_bad_xml(parser):
  1210. bad_xml = """\
  1211. <?xml version='1.0' encoding='utf-8'?>
  1212. <row>
  1213. <shape>square</shape>
  1214. <degrees>00360</degrees>
  1215. <sides>4.0</sides>
  1216. <date>2020-01-01</date>
  1217. </row>
  1218. <row>
  1219. <shape>circle</shape>
  1220. <degrees>00360</degrees>
  1221. <sides/>
  1222. <date>2021-01-01</date>
  1223. </row>
  1224. <row>
  1225. <shape>triangle</shape>
  1226. <degrees>00180</degrees>
  1227. <sides>3.0</sides>
  1228. <date>2022-01-01</date>
  1229. </row>
  1230. """
  1231. with tm.ensure_clean(filename="bad.xml") as path:
  1232. with open(path, "w", encoding="utf-8") as f:
  1233. f.write(bad_xml)
  1234. with pytest.raises(
  1235. SyntaxError,
  1236. match=(
  1237. "Extra content at the end of the document|"
  1238. "junk after document element"
  1239. ),
  1240. ):
  1241. read_xml(
  1242. path,
  1243. parser=parser,
  1244. parse_dates=["date"],
  1245. iterparse={"row": ["shape", "degrees", "sides", "date"]},
  1246. )
  1247. def test_comment(parser):
  1248. xml = """\
  1249. <!-- comment before root -->
  1250. <shapes>
  1251. <!-- comment within root -->
  1252. <shape>
  1253. <name>circle</name>
  1254. <type>2D</type>
  1255. </shape>
  1256. <shape>
  1257. <name>sphere</name>
  1258. <type>3D</type>
  1259. <!-- comment within child -->
  1260. </shape>
  1261. <!-- comment within root -->
  1262. </shapes>
  1263. <!-- comment after root -->"""
  1264. df_xpath = read_xml(StringIO(xml), xpath=".//shape", parser=parser)
  1265. df_iter = read_xml_iterparse(
  1266. xml, parser=parser, iterparse={"shape": ["name", "type"]}
  1267. )
  1268. df_expected = DataFrame(
  1269. {
  1270. "name": ["circle", "sphere"],
  1271. "type": ["2D", "3D"],
  1272. }
  1273. )
  1274. tm.assert_frame_equal(df_xpath, df_expected)
  1275. tm.assert_frame_equal(df_iter, df_expected)
  1276. def test_dtd(parser):
  1277. xml = """\
  1278. <?xml version="1.0" encoding="UTF-8"?>
  1279. <!DOCTYPE non-profits [
  1280. <!ELEMENT shapes (shape*) >
  1281. <!ELEMENT shape ( name, type )>
  1282. <!ELEMENT name (#PCDATA)>
  1283. ]>
  1284. <shapes>
  1285. <shape>
  1286. <name>circle</name>
  1287. <type>2D</type>
  1288. </shape>
  1289. <shape>
  1290. <name>sphere</name>
  1291. <type>3D</type>
  1292. </shape>
  1293. </shapes>"""
  1294. df_xpath = read_xml(StringIO(xml), xpath=".//shape", parser=parser)
  1295. df_iter = read_xml_iterparse(
  1296. xml, parser=parser, iterparse={"shape": ["name", "type"]}
  1297. )
  1298. df_expected = DataFrame(
  1299. {
  1300. "name": ["circle", "sphere"],
  1301. "type": ["2D", "3D"],
  1302. }
  1303. )
  1304. tm.assert_frame_equal(df_xpath, df_expected)
  1305. tm.assert_frame_equal(df_iter, df_expected)
  1306. def test_processing_instruction(parser):
  1307. xml = """\
  1308. <?xml version="1.0" encoding="UTF-8"?>
  1309. <?xml-stylesheet type="text/xsl" href="style.xsl"?>
  1310. <?display table-view?>
  1311. <?sort alpha-ascending?>
  1312. <?textinfo whitespace is allowed ?>
  1313. <?elementnames <shape>, <name>, <type> ?>
  1314. <shapes>
  1315. <shape>
  1316. <name>circle</name>
  1317. <type>2D</type>
  1318. </shape>
  1319. <shape>
  1320. <name>sphere</name>
  1321. <type>3D</type>
  1322. </shape>
  1323. </shapes>"""
  1324. df_xpath = read_xml(StringIO(xml), xpath=".//shape", parser=parser)
  1325. df_iter = read_xml_iterparse(
  1326. xml, parser=parser, iterparse={"shape": ["name", "type"]}
  1327. )
  1328. df_expected = DataFrame(
  1329. {
  1330. "name": ["circle", "sphere"],
  1331. "type": ["2D", "3D"],
  1332. }
  1333. )
  1334. tm.assert_frame_equal(df_xpath, df_expected)
  1335. tm.assert_frame_equal(df_iter, df_expected)
  1336. def test_no_result(xml_books, parser):
  1337. with pytest.raises(
  1338. ParserError, match="No result from selected items in iterparse."
  1339. ):
  1340. read_xml(
  1341. xml_books,
  1342. parser=parser,
  1343. iterparse={"node": ["attr1", "elem1", "elem2", "elem3"]},
  1344. )
  1345. def test_empty_data(xml_books, parser):
  1346. with pytest.raises(EmptyDataError, match="No columns to parse from file"):
  1347. read_xml(
  1348. xml_books,
  1349. parser=parser,
  1350. iterparse={"book": ["attr1", "elem1", "elem2", "elem3"]},
  1351. )
  1352. def test_online_stylesheet():
  1353. pytest.importorskip("lxml")
  1354. xml = """\
  1355. <?xml version="1.0" encoding="UTF-8"?>
  1356. <catalog>
  1357. <cd>
  1358. <title>Empire Burlesque</title>
  1359. <artist>Bob Dylan</artist>
  1360. <country>USA</country>
  1361. <company>Columbia</company>
  1362. <price>10.90</price>
  1363. <year>1985</year>
  1364. </cd>
  1365. <cd>
  1366. <title>Hide your heart</title>
  1367. <artist>Bonnie Tyler</artist>
  1368. <country>UK</country>
  1369. <company>CBS Records</company>
  1370. <price>9.90</price>
  1371. <year>1988</year>
  1372. </cd>
  1373. <cd>
  1374. <title>Greatest Hits</title>
  1375. <artist>Dolly Parton</artist>
  1376. <country>USA</country>
  1377. <company>RCA</company>
  1378. <price>9.90</price>
  1379. <year>1982</year>
  1380. </cd>
  1381. <cd>
  1382. <title>Still got the blues</title>
  1383. <artist>Gary Moore</artist>
  1384. <country>UK</country>
  1385. <company>Virgin records</company>
  1386. <price>10.20</price>
  1387. <year>1990</year>
  1388. </cd>
  1389. <cd>
  1390. <title>Eros</title>
  1391. <artist>Eros Ramazzotti</artist>
  1392. <country>EU</country>
  1393. <company>BMG</company>
  1394. <price>9.90</price>
  1395. <year>1997</year>
  1396. </cd>
  1397. <cd>
  1398. <title>One night only</title>
  1399. <artist>Bee Gees</artist>
  1400. <country>UK</country>
  1401. <company>Polydor</company>
  1402. <price>10.90</price>
  1403. <year>1998</year>
  1404. </cd>
  1405. <cd>
  1406. <title>Sylvias Mother</title>
  1407. <artist>Dr.Hook</artist>
  1408. <country>UK</country>
  1409. <company>CBS</company>
  1410. <price>8.10</price>
  1411. <year>1973</year>
  1412. </cd>
  1413. <cd>
  1414. <title>Maggie May</title>
  1415. <artist>Rod Stewart</artist>
  1416. <country>UK</country>
  1417. <company>Pickwick</company>
  1418. <price>8.50</price>
  1419. <year>1990</year>
  1420. </cd>
  1421. <cd>
  1422. <title>Romanza</title>
  1423. <artist>Andrea Bocelli</artist>
  1424. <country>EU</country>
  1425. <company>Polydor</company>
  1426. <price>10.80</price>
  1427. <year>1996</year>
  1428. </cd>
  1429. <cd>
  1430. <title>When a man loves a woman</title>
  1431. <artist>Percy Sledge</artist>
  1432. <country>USA</country>
  1433. <company>Atlantic</company>
  1434. <price>8.70</price>
  1435. <year>1987</year>
  1436. </cd>
  1437. <cd>
  1438. <title>Black angel</title>
  1439. <artist>Savage Rose</artist>
  1440. <country>EU</country>
  1441. <company>Mega</company>
  1442. <price>10.90</price>
  1443. <year>1995</year>
  1444. </cd>
  1445. <cd>
  1446. <title>1999 Grammy Nominees</title>
  1447. <artist>Many</artist>
  1448. <country>USA</country>
  1449. <company>Grammy</company>
  1450. <price>10.20</price>
  1451. <year>1999</year>
  1452. </cd>
  1453. <cd>
  1454. <title>For the good times</title>
  1455. <artist>Kenny Rogers</artist>
  1456. <country>UK</country>
  1457. <company>Mucik Master</company>
  1458. <price>8.70</price>
  1459. <year>1995</year>
  1460. </cd>
  1461. <cd>
  1462. <title>Big Willie style</title>
  1463. <artist>Will Smith</artist>
  1464. <country>USA</country>
  1465. <company>Columbia</company>
  1466. <price>9.90</price>
  1467. <year>1997</year>
  1468. </cd>
  1469. <cd>
  1470. <title>Tupelo Honey</title>
  1471. <artist>Van Morrison</artist>
  1472. <country>UK</country>
  1473. <company>Polydor</company>
  1474. <price>8.20</price>
  1475. <year>1971</year>
  1476. </cd>
  1477. <cd>
  1478. <title>Soulsville</title>
  1479. <artist>Jorn Hoel</artist>
  1480. <country>Norway</country>
  1481. <company>WEA</company>
  1482. <price>7.90</price>
  1483. <year>1996</year>
  1484. </cd>
  1485. <cd>
  1486. <title>The very best of</title>
  1487. <artist>Cat Stevens</artist>
  1488. <country>UK</country>
  1489. <company>Island</company>
  1490. <price>8.90</price>
  1491. <year>1990</year>
  1492. </cd>
  1493. <cd>
  1494. <title>Stop</title>
  1495. <artist>Sam Brown</artist>
  1496. <country>UK</country>
  1497. <company>A and M</company>
  1498. <price>8.90</price>
  1499. <year>1988</year>
  1500. </cd>
  1501. <cd>
  1502. <title>Bridge of Spies</title>
  1503. <artist>T`Pau</artist>
  1504. <country>UK</country>
  1505. <company>Siren</company>
  1506. <price>7.90</price>
  1507. <year>1987</year>
  1508. </cd>
  1509. <cd>
  1510. <title>Private Dancer</title>
  1511. <artist>Tina Turner</artist>
  1512. <country>UK</country>
  1513. <company>Capitol</company>
  1514. <price>8.90</price>
  1515. <year>1983</year>
  1516. </cd>
  1517. <cd>
  1518. <title>Midt om natten</title>
  1519. <artist>Kim Larsen</artist>
  1520. <country>EU</country>
  1521. <company>Medley</company>
  1522. <price>7.80</price>
  1523. <year>1983</year>
  1524. </cd>
  1525. <cd>
  1526. <title>Pavarotti Gala Concert</title>
  1527. <artist>Luciano Pavarotti</artist>
  1528. <country>UK</country>
  1529. <company>DECCA</company>
  1530. <price>9.90</price>
  1531. <year>1991</year>
  1532. </cd>
  1533. <cd>
  1534. <title>The dock of the bay</title>
  1535. <artist>Otis Redding</artist>
  1536. <country>USA</country>
  1537. <COMPANY>Stax Records</COMPANY>
  1538. <PRICE>7.90</PRICE>
  1539. <YEAR>1968</YEAR>
  1540. </cd>
  1541. <cd>
  1542. <title>Picture book</title>
  1543. <artist>Simply Red</artist>
  1544. <country>EU</country>
  1545. <company>Elektra</company>
  1546. <price>7.20</price>
  1547. <year>1985</year>
  1548. </cd>
  1549. <cd>
  1550. <title>Red</title>
  1551. <artist>The Communards</artist>
  1552. <country>UK</country>
  1553. <company>London</company>
  1554. <price>7.80</price>
  1555. <year>1987</year>
  1556. </cd>
  1557. <cd>
  1558. <title>Unchain my heart</title>
  1559. <artist>Joe Cocker</artist>
  1560. <country>USA</country>
  1561. <company>EMI</company>
  1562. <price>8.20</price>
  1563. <year>1987</year>
  1564. </cd>
  1565. </catalog>
  1566. """
  1567. xsl = """\
  1568. <?xml version="1.0" encoding="UTF-8"?>
  1569. <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  1570. <xsl:template match="/">
  1571. <html>
  1572. <body>
  1573. <h2>My CD Collection</h2>
  1574. <table border="1">
  1575. <tr bgcolor="#9acd32">
  1576. <th style="text-align:left">Title</th>
  1577. <th style="text-align:left">Artist</th>
  1578. </tr>
  1579. <xsl:for-each select="catalog/cd">
  1580. <tr>
  1581. <td><xsl:value-of select="title"/></td>
  1582. <td><xsl:value-of select="artist"/></td>
  1583. </tr>
  1584. </xsl:for-each>
  1585. </table>
  1586. </body>
  1587. </html>
  1588. </xsl:template>
  1589. </xsl:stylesheet>
  1590. """
  1591. df_xsl = read_xml(
  1592. StringIO(xml),
  1593. xpath=".//tr[td and position() <= 6]",
  1594. names=["title", "artist"],
  1595. stylesheet=xsl,
  1596. )
  1597. df_expected = DataFrame(
  1598. {
  1599. "title": {
  1600. 0: "Empire Burlesque",
  1601. 1: "Hide your heart",
  1602. 2: "Greatest Hits",
  1603. 3: "Still got the blues",
  1604. 4: "Eros",
  1605. },
  1606. "artist": {
  1607. 0: "Bob Dylan",
  1608. 1: "Bonnie Tyler",
  1609. 2: "Dolly Parton",
  1610. 3: "Gary Moore",
  1611. 4: "Eros Ramazzotti",
  1612. },
  1613. }
  1614. )
  1615. tm.assert_frame_equal(df_expected, df_xsl)
  1616. # COMPRESSION
  1617. def test_compression_read(parser, compression_only):
  1618. with tm.ensure_clean() as comp_path:
  1619. geom_df.to_xml(
  1620. comp_path, index=False, parser=parser, compression=compression_only
  1621. )
  1622. df_xpath = read_xml(comp_path, parser=parser, compression=compression_only)
  1623. df_iter = read_xml_iterparse_comp(
  1624. comp_path,
  1625. compression_only,
  1626. parser=parser,
  1627. iterparse={"row": ["shape", "degrees", "sides"]},
  1628. compression=compression_only,
  1629. )
  1630. tm.assert_frame_equal(df_xpath, geom_df)
  1631. tm.assert_frame_equal(df_iter, geom_df)
  1632. def test_wrong_compression(parser, compression, compression_only):
  1633. actual_compression = compression
  1634. attempted_compression = compression_only
  1635. if actual_compression == attempted_compression:
  1636. pytest.skip(f"{actual_compression} == {attempted_compression}")
  1637. errors = {
  1638. "bz2": (OSError, "Invalid data stream"),
  1639. "gzip": (OSError, "Not a gzipped file"),
  1640. "zip": (BadZipFile, "File is not a zip file"),
  1641. "tar": (ReadError, "file could not be opened successfully"),
  1642. }
  1643. zstd = import_optional_dependency("zstandard", errors="ignore")
  1644. if zstd is not None:
  1645. errors["zstd"] = (zstd.ZstdError, "Unknown frame descriptor")
  1646. lzma = import_optional_dependency("lzma", errors="ignore")
  1647. if lzma is not None:
  1648. errors["xz"] = (LZMAError, "Input format not supported by decoder")
  1649. error_cls, error_str = errors[attempted_compression]
  1650. with tm.ensure_clean() as path:
  1651. geom_df.to_xml(path, parser=parser, compression=actual_compression)
  1652. with pytest.raises(error_cls, match=error_str):
  1653. read_xml(path, parser=parser, compression=attempted_compression)
  1654. def test_unsuported_compression(parser):
  1655. with pytest.raises(ValueError, match="Unrecognized compression type"):
  1656. with tm.ensure_clean() as path:
  1657. read_xml(path, parser=parser, compression="7z")
  1658. # STORAGE OPTIONS
  1659. @pytest.mark.network
  1660. @pytest.mark.single_cpu
  1661. def test_s3_parser_consistency(s3_public_bucket_with_data, s3so):
  1662. pytest.importorskip("s3fs")
  1663. pytest.importorskip("lxml")
  1664. s3 = f"s3://{s3_public_bucket_with_data.name}/books.xml"
  1665. df_lxml = read_xml(s3, parser="lxml", storage_options=s3so)
  1666. df_etree = read_xml(s3, parser="etree", storage_options=s3so)
  1667. tm.assert_frame_equal(df_lxml, df_etree)
  1668. def test_read_xml_nullable_dtypes(
  1669. parser, string_storage, dtype_backend, using_infer_string
  1670. ):
  1671. # GH#50500
  1672. data = """<?xml version='1.0' encoding='utf-8'?>
  1673. <data xmlns="http://example.com">
  1674. <row>
  1675. <a>x</a>
  1676. <b>1</b>
  1677. <c>4.0</c>
  1678. <d>x</d>
  1679. <e>2</e>
  1680. <f>4.0</f>
  1681. <g></g>
  1682. <h>True</h>
  1683. <i>False</i>
  1684. </row>
  1685. <row>
  1686. <a>y</a>
  1687. <b>2</b>
  1688. <c>5.0</c>
  1689. <d></d>
  1690. <e></e>
  1691. <f></f>
  1692. <g></g>
  1693. <h>False</h>
  1694. <i></i>
  1695. </row>
  1696. </data>"""
  1697. with pd.option_context("mode.string_storage", string_storage):
  1698. result = read_xml(StringIO(data), parser=parser, dtype_backend=dtype_backend)
  1699. if dtype_backend == "pyarrow":
  1700. pa = pytest.importorskip("pyarrow")
  1701. string_dtype = pd.ArrowDtype(pa.string())
  1702. else:
  1703. string_dtype = pd.StringDtype(string_storage)
  1704. expected = DataFrame(
  1705. {
  1706. "a": Series(["x", "y"], dtype=string_dtype),
  1707. "b": Series([1, 2], dtype="Int64"),
  1708. "c": Series([4.0, 5.0], dtype="Float64"),
  1709. "d": Series(["x", None], dtype=string_dtype),
  1710. "e": Series([2, NA], dtype="Int64"),
  1711. "f": Series([4.0, NA], dtype="Float64"),
  1712. "g": Series([NA, NA], dtype="Int64"),
  1713. "h": Series([True, False], dtype="boolean"),
  1714. "i": Series([False, NA], dtype="boolean"),
  1715. }
  1716. )
  1717. if dtype_backend == "pyarrow":
  1718. pa = pytest.importorskip("pyarrow")
  1719. from pandas.arrays import ArrowExtensionArray
  1720. expected = DataFrame(
  1721. {
  1722. col: ArrowExtensionArray(pa.array(expected[col], from_pandas=True))
  1723. for col in expected.columns
  1724. }
  1725. )
  1726. expected["g"] = ArrowExtensionArray(pa.array([None, None]))
  1727. # the storage of the str columns' Index is also affected by the
  1728. # string_storage setting -> ignore that for checking the result
  1729. tm.assert_frame_equal(result, expected, check_column_type=False)
  1730. def test_invalid_dtype_backend():
  1731. msg = (
  1732. "dtype_backend numpy is invalid, only 'numpy_nullable' and "
  1733. "'pyarrow' are allowed."
  1734. )
  1735. with pytest.raises(ValueError, match=msg):
  1736. read_xml("test", dtype_backend="numpy")