test_to_xml.py 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349
  1. from __future__ import annotations
  2. from io import (
  3. BytesIO,
  4. StringIO,
  5. )
  6. import os
  7. import numpy as np
  8. import pytest
  9. import pandas.util._test_decorators as td
  10. from pandas import (
  11. NA,
  12. DataFrame,
  13. Index,
  14. )
  15. import pandas._testing as tm
  16. from pandas.tests.io.test_compression import _compression_to_extension
  17. from pandas.io.common import get_handle
  18. from pandas.io.xml import read_xml
  19. # CHECKLIST
  20. # [x] - ValueError: "Values for parser can only be lxml or etree."
  21. # etree
  22. # [x] - ImportError: "lxml not found, please install or use the etree parser."
  23. # [X] - TypeError: "...is not a valid type for attr_cols"
  24. # [X] - TypeError: "...is not a valid type for elem_cols"
  25. # [X] - LookupError: "unknown encoding"
  26. # [X] - KeyError: "...is not included in namespaces"
  27. # [X] - KeyError: "no valid column"
  28. # [X] - ValueError: "To use stylesheet, you need lxml installed..."
  29. # [] - OSError: (NEED PERMISSOIN ISSUE, DISK FULL, ETC.)
  30. # [X] - FileNotFoundError: "No such file or directory"
  31. # [X] - PermissionError: "Forbidden"
  32. # lxml
  33. # [X] - TypeError: "...is not a valid type for attr_cols"
  34. # [X] - TypeError: "...is not a valid type for elem_cols"
  35. # [X] - LookupError: "unknown encoding"
  36. # [] - OSError: (NEED PERMISSOIN ISSUE, DISK FULL, ETC.)
  37. # [X] - FileNotFoundError: "No such file or directory"
  38. # [X] - KeyError: "...is not included in namespaces"
  39. # [X] - KeyError: "no valid column"
  40. # [X] - ValueError: "stylesheet is not a url, file, or xml string."
  41. # [] - LookupError: (NEED WRONG ENCODING FOR FILE OUTPUT)
  42. # [] - URLError: (USUALLY DUE TO NETWORKING)
  43. # [] - HTTPError: (NEED AN ONLINE STYLESHEET)
  44. # [X] - OSError: "failed to load external entity"
  45. # [X] - XMLSyntaxError: "Opening and ending tag mismatch"
  46. # [X] - XSLTApplyError: "Cannot resolve URI"
  47. # [X] - XSLTParseError: "failed to compile"
  48. # [X] - PermissionError: "Forbidden"
  49. geom_df = DataFrame(
  50. {
  51. "shape": ["square", "circle", "triangle"],
  52. "degrees": [360, 360, 180],
  53. "sides": [4, np.nan, 3],
  54. }
  55. )
  56. planet_df = DataFrame(
  57. {
  58. "planet": [
  59. "Mercury",
  60. "Venus",
  61. "Earth",
  62. "Mars",
  63. "Jupiter",
  64. "Saturn",
  65. "Uranus",
  66. "Neptune",
  67. ],
  68. "type": [
  69. "terrestrial",
  70. "terrestrial",
  71. "terrestrial",
  72. "terrestrial",
  73. "gas giant",
  74. "gas giant",
  75. "ice giant",
  76. "ice giant",
  77. ],
  78. "location": [
  79. "inner",
  80. "inner",
  81. "inner",
  82. "inner",
  83. "outer",
  84. "outer",
  85. "outer",
  86. "outer",
  87. ],
  88. "mass": [
  89. 0.330114,
  90. 4.86747,
  91. 5.97237,
  92. 0.641712,
  93. 1898.187,
  94. 568.3174,
  95. 86.8127,
  96. 102.4126,
  97. ],
  98. }
  99. )
  100. from_file_expected = """\
  101. <?xml version='1.0' encoding='utf-8'?>
  102. <data>
  103. <row>
  104. <index>0</index>
  105. <category>cooking</category>
  106. <title>Everyday Italian</title>
  107. <author>Giada De Laurentiis</author>
  108. <year>2005</year>
  109. <price>30.0</price>
  110. </row>
  111. <row>
  112. <index>1</index>
  113. <category>children</category>
  114. <title>Harry Potter</title>
  115. <author>J K. Rowling</author>
  116. <year>2005</year>
  117. <price>29.99</price>
  118. </row>
  119. <row>
  120. <index>2</index>
  121. <category>web</category>
  122. <title>Learning XML</title>
  123. <author>Erik T. Ray</author>
  124. <year>2003</year>
  125. <price>39.95</price>
  126. </row>
  127. </data>"""
  128. def equalize_decl(doc):
  129. # etree and lxml differ on quotes and case in xml declaration
  130. if doc is not None:
  131. doc = doc.replace(
  132. '<?xml version="1.0" encoding="utf-8"?',
  133. "<?xml version='1.0' encoding='utf-8'?",
  134. )
  135. return doc
  136. @pytest.fixture(params=["rb", "r"])
  137. def mode(request):
  138. return request.param
  139. @pytest.fixture(params=[pytest.param("lxml", marks=td.skip_if_no("lxml")), "etree"])
  140. def parser(request):
  141. return request.param
  142. # FILE OUTPUT
  143. def test_file_output_str_read(datapath, parser):
  144. filename = datapath("io", "data", "xml", "books.xml")
  145. df_file = read_xml(filename, parser=parser)
  146. with tm.ensure_clean("test.xml") as path:
  147. df_file.to_xml(path, parser=parser)
  148. with open(path, "rb") as f:
  149. output = f.read().decode("utf-8").strip()
  150. output = equalize_decl(output)
  151. assert output == from_file_expected
  152. def test_file_output_bytes_read(datapath, parser):
  153. filename = datapath("io", "data", "xml", "books.xml")
  154. df_file = read_xml(filename, parser=parser)
  155. with tm.ensure_clean("test.xml") as path:
  156. df_file.to_xml(path, parser=parser)
  157. with open(path, "rb") as f:
  158. output = f.read().decode("utf-8").strip()
  159. output = equalize_decl(output)
  160. assert output == from_file_expected
  161. def test_str_output(datapath, parser):
  162. filename = datapath("io", "data", "xml", "books.xml")
  163. df_file = read_xml(filename, parser=parser)
  164. output = df_file.to_xml(parser=parser)
  165. output = equalize_decl(output)
  166. assert output == from_file_expected
  167. def test_wrong_file_path(parser):
  168. path = "/my/fake/path/output.xml"
  169. with pytest.raises(
  170. OSError,
  171. match=(r"Cannot save file into a non-existent directory: .*path"),
  172. ):
  173. geom_df.to_xml(path, parser=parser)
  174. # INDEX
  175. def test_index_false(datapath, parser):
  176. expected = """\
  177. <?xml version='1.0' encoding='utf-8'?>
  178. <data>
  179. <row>
  180. <category>cooking</category>
  181. <title>Everyday Italian</title>
  182. <author>Giada De Laurentiis</author>
  183. <year>2005</year>
  184. <price>30.0</price>
  185. </row>
  186. <row>
  187. <category>children</category>
  188. <title>Harry Potter</title>
  189. <author>J K. Rowling</author>
  190. <year>2005</year>
  191. <price>29.99</price>
  192. </row>
  193. <row>
  194. <category>web</category>
  195. <title>Learning XML</title>
  196. <author>Erik T. Ray</author>
  197. <year>2003</year>
  198. <price>39.95</price>
  199. </row>
  200. </data>"""
  201. filename = datapath("io", "data", "xml", "books.xml")
  202. df_file = read_xml(filename, parser=parser)
  203. with tm.ensure_clean("test.xml") as path:
  204. df_file.to_xml(path, index=False, parser=parser)
  205. with open(path, "rb") as f:
  206. output = f.read().decode("utf-8").strip()
  207. output = equalize_decl(output)
  208. assert output == expected
  209. def test_index_false_rename_row_root(datapath, parser):
  210. expected = """\
  211. <?xml version='1.0' encoding='utf-8'?>
  212. <books>
  213. <book>
  214. <category>cooking</category>
  215. <title>Everyday Italian</title>
  216. <author>Giada De Laurentiis</author>
  217. <year>2005</year>
  218. <price>30.0</price>
  219. </book>
  220. <book>
  221. <category>children</category>
  222. <title>Harry Potter</title>
  223. <author>J K. Rowling</author>
  224. <year>2005</year>
  225. <price>29.99</price>
  226. </book>
  227. <book>
  228. <category>web</category>
  229. <title>Learning XML</title>
  230. <author>Erik T. Ray</author>
  231. <year>2003</year>
  232. <price>39.95</price>
  233. </book>
  234. </books>"""
  235. filename = datapath("io", "data", "xml", "books.xml")
  236. df_file = read_xml(filename, parser=parser)
  237. with tm.ensure_clean("test.xml") as path:
  238. df_file.to_xml(
  239. path, index=False, root_name="books", row_name="book", parser=parser
  240. )
  241. with open(path, "rb") as f:
  242. output = f.read().decode("utf-8").strip()
  243. output = equalize_decl(output)
  244. assert output == expected
  245. @pytest.mark.parametrize(
  246. "offset_index", [list(range(10, 13)), [str(i) for i in range(10, 13)]]
  247. )
  248. def test_index_false_with_offset_input_index(parser, offset_index):
  249. """
  250. Tests that the output does not contain the `<index>` field when the index of the
  251. input Dataframe has an offset.
  252. This is a regression test for issue #42458.
  253. """
  254. expected = """\
  255. <?xml version='1.0' encoding='utf-8'?>
  256. <data>
  257. <row>
  258. <shape>square</shape>
  259. <degrees>360</degrees>
  260. <sides>4.0</sides>
  261. </row>
  262. <row>
  263. <shape>circle</shape>
  264. <degrees>360</degrees>
  265. <sides/>
  266. </row>
  267. <row>
  268. <shape>triangle</shape>
  269. <degrees>180</degrees>
  270. <sides>3.0</sides>
  271. </row>
  272. </data>"""
  273. offset_geom_df = geom_df.copy()
  274. offset_geom_df.index = Index(offset_index)
  275. output = offset_geom_df.to_xml(index=False, parser=parser)
  276. output = equalize_decl(output)
  277. assert output == expected
  278. # NA_REP
  279. na_expected = """\
  280. <?xml version='1.0' encoding='utf-8'?>
  281. <data>
  282. <row>
  283. <index>0</index>
  284. <shape>square</shape>
  285. <degrees>360</degrees>
  286. <sides>4.0</sides>
  287. </row>
  288. <row>
  289. <index>1</index>
  290. <shape>circle</shape>
  291. <degrees>360</degrees>
  292. <sides/>
  293. </row>
  294. <row>
  295. <index>2</index>
  296. <shape>triangle</shape>
  297. <degrees>180</degrees>
  298. <sides>3.0</sides>
  299. </row>
  300. </data>"""
  301. def test_na_elem_output(parser):
  302. output = geom_df.to_xml(parser=parser)
  303. output = equalize_decl(output)
  304. assert output == na_expected
  305. def test_na_empty_str_elem_option(parser):
  306. output = geom_df.to_xml(na_rep="", parser=parser)
  307. output = equalize_decl(output)
  308. assert output == na_expected
  309. def test_na_empty_elem_option(parser):
  310. expected = """\
  311. <?xml version='1.0' encoding='utf-8'?>
  312. <data>
  313. <row>
  314. <index>0</index>
  315. <shape>square</shape>
  316. <degrees>360</degrees>
  317. <sides>4.0</sides>
  318. </row>
  319. <row>
  320. <index>1</index>
  321. <shape>circle</shape>
  322. <degrees>360</degrees>
  323. <sides>0.0</sides>
  324. </row>
  325. <row>
  326. <index>2</index>
  327. <shape>triangle</shape>
  328. <degrees>180</degrees>
  329. <sides>3.0</sides>
  330. </row>
  331. </data>"""
  332. output = geom_df.to_xml(na_rep="0.0", parser=parser)
  333. output = equalize_decl(output)
  334. assert output == expected
  335. # ATTR_COLS
  336. def test_attrs_cols_nan_output(parser):
  337. expected = """\
  338. <?xml version='1.0' encoding='utf-8'?>
  339. <data>
  340. <row index="0" shape="square" degrees="360" sides="4.0"/>
  341. <row index="1" shape="circle" degrees="360"/>
  342. <row index="2" shape="triangle" degrees="180" sides="3.0"/>
  343. </data>"""
  344. output = geom_df.to_xml(attr_cols=["shape", "degrees", "sides"], parser=parser)
  345. output = equalize_decl(output)
  346. assert output == expected
  347. def test_attrs_cols_prefix(parser):
  348. expected = """\
  349. <?xml version='1.0' encoding='utf-8'?>
  350. <doc:data xmlns:doc="http://example.xom">
  351. <doc:row doc:index="0" doc:shape="square" \
  352. doc:degrees="360" doc:sides="4.0"/>
  353. <doc:row doc:index="1" doc:shape="circle" \
  354. doc:degrees="360"/>
  355. <doc:row doc:index="2" doc:shape="triangle" \
  356. doc:degrees="180" doc:sides="3.0"/>
  357. </doc:data>"""
  358. output = geom_df.to_xml(
  359. attr_cols=["index", "shape", "degrees", "sides"],
  360. namespaces={"doc": "http://example.xom"},
  361. prefix="doc",
  362. parser=parser,
  363. )
  364. output = equalize_decl(output)
  365. assert output == expected
  366. def test_attrs_unknown_column(parser):
  367. with pytest.raises(KeyError, match=("no valid column")):
  368. geom_df.to_xml(attr_cols=["shape", "degree", "sides"], parser=parser)
  369. def test_attrs_wrong_type(parser):
  370. with pytest.raises(TypeError, match=("is not a valid type for attr_cols")):
  371. geom_df.to_xml(attr_cols='"shape", "degree", "sides"', parser=parser)
  372. # ELEM_COLS
  373. def test_elems_cols_nan_output(parser):
  374. elems_cols_expected = """\
  375. <?xml version='1.0' encoding='utf-8'?>
  376. <data>
  377. <row>
  378. <degrees>360</degrees>
  379. <sides>4.0</sides>
  380. <shape>square</shape>
  381. </row>
  382. <row>
  383. <degrees>360</degrees>
  384. <sides/>
  385. <shape>circle</shape>
  386. </row>
  387. <row>
  388. <degrees>180</degrees>
  389. <sides>3.0</sides>
  390. <shape>triangle</shape>
  391. </row>
  392. </data>"""
  393. output = geom_df.to_xml(
  394. index=False, elem_cols=["degrees", "sides", "shape"], parser=parser
  395. )
  396. output = equalize_decl(output)
  397. assert output == elems_cols_expected
  398. def test_elems_unknown_column(parser):
  399. with pytest.raises(KeyError, match=("no valid column")):
  400. geom_df.to_xml(elem_cols=["shape", "degree", "sides"], parser=parser)
  401. def test_elems_wrong_type(parser):
  402. with pytest.raises(TypeError, match=("is not a valid type for elem_cols")):
  403. geom_df.to_xml(elem_cols='"shape", "degree", "sides"', parser=parser)
  404. def test_elems_and_attrs_cols(parser):
  405. elems_cols_expected = """\
  406. <?xml version='1.0' encoding='utf-8'?>
  407. <data>
  408. <row shape="square">
  409. <degrees>360</degrees>
  410. <sides>4.0</sides>
  411. </row>
  412. <row shape="circle">
  413. <degrees>360</degrees>
  414. <sides/>
  415. </row>
  416. <row shape="triangle">
  417. <degrees>180</degrees>
  418. <sides>3.0</sides>
  419. </row>
  420. </data>"""
  421. output = geom_df.to_xml(
  422. index=False,
  423. elem_cols=["degrees", "sides"],
  424. attr_cols=["shape"],
  425. parser=parser,
  426. )
  427. output = equalize_decl(output)
  428. assert output == elems_cols_expected
  429. # HIERARCHICAL COLUMNS
  430. def test_hierarchical_columns(parser):
  431. expected = """\
  432. <?xml version='1.0' encoding='utf-8'?>
  433. <data>
  434. <row>
  435. <location>inner</location>
  436. <type>terrestrial</type>
  437. <count_mass>4</count_mass>
  438. <sum_mass>11.81</sum_mass>
  439. <mean_mass>2.95</mean_mass>
  440. </row>
  441. <row>
  442. <location>outer</location>
  443. <type>gas giant</type>
  444. <count_mass>2</count_mass>
  445. <sum_mass>2466.5</sum_mass>
  446. <mean_mass>1233.25</mean_mass>
  447. </row>
  448. <row>
  449. <location>outer</location>
  450. <type>ice giant</type>
  451. <count_mass>2</count_mass>
  452. <sum_mass>189.23</sum_mass>
  453. <mean_mass>94.61</mean_mass>
  454. </row>
  455. <row>
  456. <location>All</location>
  457. <type/>
  458. <count_mass>8</count_mass>
  459. <sum_mass>2667.54</sum_mass>
  460. <mean_mass>333.44</mean_mass>
  461. </row>
  462. </data>"""
  463. pvt = planet_df.pivot_table(
  464. index=["location", "type"],
  465. values="mass",
  466. aggfunc=["count", "sum", "mean"],
  467. margins=True,
  468. ).round(2)
  469. output = pvt.to_xml(parser=parser)
  470. output = equalize_decl(output)
  471. assert output == expected
  472. def test_hierarchical_attrs_columns(parser):
  473. expected = """\
  474. <?xml version='1.0' encoding='utf-8'?>
  475. <data>
  476. <row location="inner" type="terrestrial" count_mass="4" \
  477. sum_mass="11.81" mean_mass="2.95"/>
  478. <row location="outer" type="gas giant" count_mass="2" \
  479. sum_mass="2466.5" mean_mass="1233.25"/>
  480. <row location="outer" type="ice giant" count_mass="2" \
  481. sum_mass="189.23" mean_mass="94.61"/>
  482. <row location="All" type="" count_mass="8" \
  483. sum_mass="2667.54" mean_mass="333.44"/>
  484. </data>"""
  485. pvt = planet_df.pivot_table(
  486. index=["location", "type"],
  487. values="mass",
  488. aggfunc=["count", "sum", "mean"],
  489. margins=True,
  490. ).round(2)
  491. output = pvt.to_xml(attr_cols=list(pvt.reset_index().columns.values), parser=parser)
  492. output = equalize_decl(output)
  493. assert output == expected
  494. # MULTIINDEX
  495. def test_multi_index(parser):
  496. expected = """\
  497. <?xml version='1.0' encoding='utf-8'?>
  498. <data>
  499. <row>
  500. <location>inner</location>
  501. <type>terrestrial</type>
  502. <count>4</count>
  503. <sum>11.81</sum>
  504. <mean>2.95</mean>
  505. </row>
  506. <row>
  507. <location>outer</location>
  508. <type>gas giant</type>
  509. <count>2</count>
  510. <sum>2466.5</sum>
  511. <mean>1233.25</mean>
  512. </row>
  513. <row>
  514. <location>outer</location>
  515. <type>ice giant</type>
  516. <count>2</count>
  517. <sum>189.23</sum>
  518. <mean>94.61</mean>
  519. </row>
  520. </data>"""
  521. agg = (
  522. planet_df.groupby(["location", "type"])["mass"]
  523. .agg(["count", "sum", "mean"])
  524. .round(2)
  525. )
  526. output = agg.to_xml(parser=parser)
  527. output = equalize_decl(output)
  528. assert output == expected
  529. def test_multi_index_attrs_cols(parser):
  530. expected = """\
  531. <?xml version='1.0' encoding='utf-8'?>
  532. <data>
  533. <row location="inner" type="terrestrial" count="4" \
  534. sum="11.81" mean="2.95"/>
  535. <row location="outer" type="gas giant" count="2" \
  536. sum="2466.5" mean="1233.25"/>
  537. <row location="outer" type="ice giant" count="2" \
  538. sum="189.23" mean="94.61"/>
  539. </data>"""
  540. agg = (
  541. planet_df.groupby(["location", "type"])["mass"]
  542. .agg(["count", "sum", "mean"])
  543. .round(2)
  544. )
  545. output = agg.to_xml(attr_cols=list(agg.reset_index().columns.values), parser=parser)
  546. output = equalize_decl(output)
  547. assert output == expected
  548. # NAMESPACE
  549. def test_default_namespace(parser):
  550. expected = """\
  551. <?xml version='1.0' encoding='utf-8'?>
  552. <data xmlns="http://example.com">
  553. <row>
  554. <index>0</index>
  555. <shape>square</shape>
  556. <degrees>360</degrees>
  557. <sides>4.0</sides>
  558. </row>
  559. <row>
  560. <index>1</index>
  561. <shape>circle</shape>
  562. <degrees>360</degrees>
  563. <sides/>
  564. </row>
  565. <row>
  566. <index>2</index>
  567. <shape>triangle</shape>
  568. <degrees>180</degrees>
  569. <sides>3.0</sides>
  570. </row>
  571. </data>"""
  572. output = geom_df.to_xml(namespaces={"": "http://example.com"}, parser=parser)
  573. output = equalize_decl(output)
  574. assert output == expected
  575. # PREFIX
  576. def test_namespace_prefix(parser):
  577. expected = """\
  578. <?xml version='1.0' encoding='utf-8'?>
  579. <doc:data xmlns:doc="http://example.com">
  580. <doc:row>
  581. <doc:index>0</doc:index>
  582. <doc:shape>square</doc:shape>
  583. <doc:degrees>360</doc:degrees>
  584. <doc:sides>4.0</doc:sides>
  585. </doc:row>
  586. <doc:row>
  587. <doc:index>1</doc:index>
  588. <doc:shape>circle</doc:shape>
  589. <doc:degrees>360</doc:degrees>
  590. <doc:sides/>
  591. </doc:row>
  592. <doc:row>
  593. <doc:index>2</doc:index>
  594. <doc:shape>triangle</doc:shape>
  595. <doc:degrees>180</doc:degrees>
  596. <doc:sides>3.0</doc:sides>
  597. </doc:row>
  598. </doc:data>"""
  599. output = geom_df.to_xml(
  600. namespaces={"doc": "http://example.com"}, prefix="doc", parser=parser
  601. )
  602. output = equalize_decl(output)
  603. assert output == expected
  604. def test_missing_prefix_in_nmsp(parser):
  605. with pytest.raises(KeyError, match=("doc is not included in namespaces")):
  606. geom_df.to_xml(
  607. namespaces={"": "http://example.com"}, prefix="doc", parser=parser
  608. )
  609. def test_namespace_prefix_and_default(parser):
  610. expected = """\
  611. <?xml version='1.0' encoding='utf-8'?>
  612. <doc:data xmlns="http://example.com" xmlns:doc="http://other.org">
  613. <doc:row>
  614. <doc:index>0</doc:index>
  615. <doc:shape>square</doc:shape>
  616. <doc:degrees>360</doc:degrees>
  617. <doc:sides>4.0</doc:sides>
  618. </doc:row>
  619. <doc:row>
  620. <doc:index>1</doc:index>
  621. <doc:shape>circle</doc:shape>
  622. <doc:degrees>360</doc:degrees>
  623. <doc:sides/>
  624. </doc:row>
  625. <doc:row>
  626. <doc:index>2</doc:index>
  627. <doc:shape>triangle</doc:shape>
  628. <doc:degrees>180</doc:degrees>
  629. <doc:sides>3.0</doc:sides>
  630. </doc:row>
  631. </doc:data>"""
  632. output = geom_df.to_xml(
  633. namespaces={"": "http://example.com", "doc": "http://other.org"},
  634. prefix="doc",
  635. parser=parser,
  636. )
  637. output = equalize_decl(output)
  638. if output is not None:
  639. # etree and lxml differs on order of namespace prefixes
  640. output = output.replace(
  641. 'xmlns:doc="http://other.org" xmlns="http://example.com"',
  642. 'xmlns="http://example.com" xmlns:doc="http://other.org"',
  643. )
  644. assert output == expected
  645. # ENCODING
  646. encoding_expected = """\
  647. <?xml version='1.0' encoding='ISO-8859-1'?>
  648. <data>
  649. <row>
  650. <index>0</index>
  651. <rank>1</rank>
  652. <malename>José</malename>
  653. <femalename>Sofía</femalename>
  654. </row>
  655. <row>
  656. <index>1</index>
  657. <rank>2</rank>
  658. <malename>Luis</malename>
  659. <femalename>Valentina</femalename>
  660. </row>
  661. <row>
  662. <index>2</index>
  663. <rank>3</rank>
  664. <malename>Carlos</malename>
  665. <femalename>Isabella</femalename>
  666. </row>
  667. <row>
  668. <index>3</index>
  669. <rank>4</rank>
  670. <malename>Juan</malename>
  671. <femalename>Camila</femalename>
  672. </row>
  673. <row>
  674. <index>4</index>
  675. <rank>5</rank>
  676. <malename>Jorge</malename>
  677. <femalename>Valeria</femalename>
  678. </row>
  679. </data>"""
  680. def test_encoding_option_str(datapath, parser):
  681. filename = datapath("io", "data", "xml", "baby_names.xml")
  682. df_file = read_xml(filename, parser=parser, encoding="ISO-8859-1").head(5)
  683. output = df_file.to_xml(encoding="ISO-8859-1", parser=parser)
  684. if output is not None:
  685. # etree and lxml differ on quotes and case in xml declaration
  686. output = output.replace(
  687. '<?xml version="1.0" encoding="ISO-8859-1"?',
  688. "<?xml version='1.0' encoding='ISO-8859-1'?",
  689. )
  690. assert output == encoding_expected
  691. @td.skip_if_no("lxml")
  692. def test_correct_encoding_file(datapath):
  693. filename = datapath("io", "data", "xml", "baby_names.xml")
  694. df_file = read_xml(filename, encoding="ISO-8859-1", parser="lxml")
  695. with tm.ensure_clean("test.xml") as path:
  696. df_file.to_xml(path, index=False, encoding="ISO-8859-1", parser="lxml")
  697. @td.skip_if_no("lxml")
  698. @pytest.mark.parametrize("encoding", ["UTF-8", "UTF-16", "ISO-8859-1"])
  699. def test_wrong_encoding_option_lxml(datapath, parser, encoding):
  700. filename = datapath("io", "data", "xml", "baby_names.xml")
  701. df_file = read_xml(filename, encoding="ISO-8859-1", parser="lxml")
  702. with tm.ensure_clean("test.xml") as path:
  703. df_file.to_xml(path, index=False, encoding=encoding, parser=parser)
  704. def test_misspelled_encoding(parser):
  705. with pytest.raises(LookupError, match=("unknown encoding")):
  706. geom_df.to_xml(encoding="uft-8", parser=parser)
  707. # PRETTY PRINT
  708. @td.skip_if_no("lxml")
  709. def test_xml_declaration_pretty_print():
  710. expected = """\
  711. <data>
  712. <row>
  713. <index>0</index>
  714. <shape>square</shape>
  715. <degrees>360</degrees>
  716. <sides>4.0</sides>
  717. </row>
  718. <row>
  719. <index>1</index>
  720. <shape>circle</shape>
  721. <degrees>360</degrees>
  722. <sides/>
  723. </row>
  724. <row>
  725. <index>2</index>
  726. <shape>triangle</shape>
  727. <degrees>180</degrees>
  728. <sides>3.0</sides>
  729. </row>
  730. </data>"""
  731. output = geom_df.to_xml(xml_declaration=False)
  732. assert output == expected
  733. def test_no_pretty_print_with_decl(parser):
  734. expected = (
  735. "<?xml version='1.0' encoding='utf-8'?>\n"
  736. "<data><row><index>0</index><shape>square</shape>"
  737. "<degrees>360</degrees><sides>4.0</sides></row><row>"
  738. "<index>1</index><shape>circle</shape><degrees>360"
  739. "</degrees><sides/></row><row><index>2</index><shape>"
  740. "triangle</shape><degrees>180</degrees><sides>3.0</sides>"
  741. "</row></data>"
  742. )
  743. output = geom_df.to_xml(pretty_print=False, parser=parser)
  744. output = equalize_decl(output)
  745. # etree adds space for closed tags
  746. if output is not None:
  747. output = output.replace(" />", "/>")
  748. assert output == expected
  749. def test_no_pretty_print_no_decl(parser):
  750. expected = (
  751. "<data><row><index>0</index><shape>square</shape>"
  752. "<degrees>360</degrees><sides>4.0</sides></row><row>"
  753. "<index>1</index><shape>circle</shape><degrees>360"
  754. "</degrees><sides/></row><row><index>2</index><shape>"
  755. "triangle</shape><degrees>180</degrees><sides>3.0</sides>"
  756. "</row></data>"
  757. )
  758. output = geom_df.to_xml(xml_declaration=False, pretty_print=False, parser=parser)
  759. # etree adds space for closed tags
  760. if output is not None:
  761. output = output.replace(" />", "/>")
  762. assert output == expected
  763. # PARSER
  764. @td.skip_if_installed("lxml")
  765. def test_default_parser_no_lxml():
  766. with pytest.raises(
  767. ImportError, match=("lxml not found, please install or use the etree parser.")
  768. ):
  769. geom_df.to_xml()
  770. def test_unknown_parser():
  771. with pytest.raises(
  772. ValueError, match=("Values for parser can only be lxml or etree.")
  773. ):
  774. geom_df.to_xml(parser="bs4")
  775. # STYLESHEET
  776. xsl_expected = """\
  777. <?xml version="1.0" encoding="utf-8"?>
  778. <data>
  779. <row>
  780. <field field="index">0</field>
  781. <field field="shape">square</field>
  782. <field field="degrees">360</field>
  783. <field field="sides">4.0</field>
  784. </row>
  785. <row>
  786. <field field="index">1</field>
  787. <field field="shape">circle</field>
  788. <field field="degrees">360</field>
  789. <field field="sides"/>
  790. </row>
  791. <row>
  792. <field field="index">2</field>
  793. <field field="shape">triangle</field>
  794. <field field="degrees">180</field>
  795. <field field="sides">3.0</field>
  796. </row>
  797. </data>"""
  798. @td.skip_if_no("lxml")
  799. def test_stylesheet_file_like(datapath, mode):
  800. xsl = datapath("io", "data", "xml", "row_field_output.xsl")
  801. with open(xsl, mode) as f:
  802. assert geom_df.to_xml(stylesheet=f) == xsl_expected
  803. @td.skip_if_no("lxml")
  804. def test_stylesheet_io(datapath, mode):
  805. xsl_path = datapath("io", "data", "xml", "row_field_output.xsl")
  806. xsl_obj: BytesIO | StringIO
  807. with open(xsl_path, mode) as f:
  808. if mode == "rb":
  809. xsl_obj = BytesIO(f.read())
  810. else:
  811. xsl_obj = StringIO(f.read())
  812. output = geom_df.to_xml(stylesheet=xsl_obj)
  813. assert output == xsl_expected
  814. @td.skip_if_no("lxml")
  815. def test_stylesheet_buffered_reader(datapath, mode):
  816. xsl = datapath("io", "data", "xml", "row_field_output.xsl")
  817. with open(xsl, mode) as f:
  818. xsl_obj = f.read()
  819. output = geom_df.to_xml(stylesheet=xsl_obj)
  820. assert output == xsl_expected
  821. @td.skip_if_no("lxml")
  822. def test_stylesheet_wrong_path():
  823. from lxml.etree import XMLSyntaxError
  824. xsl = os.path.join("data", "xml", "row_field_output.xslt")
  825. with pytest.raises(
  826. XMLSyntaxError,
  827. match=("Start tag expected, '<' not found"),
  828. ):
  829. geom_df.to_xml(stylesheet=xsl)
  830. @td.skip_if_no("lxml")
  831. @pytest.mark.parametrize("val", ["", b""])
  832. def test_empty_string_stylesheet(val):
  833. from lxml.etree import XMLSyntaxError
  834. msg = "|".join(
  835. [
  836. "Document is empty",
  837. "Start tag expected, '<' not found",
  838. # Seen on Mac with lxml 4.9.1
  839. r"None \(line 0\)",
  840. ]
  841. )
  842. with pytest.raises(XMLSyntaxError, match=msg):
  843. geom_df.to_xml(stylesheet=val)
  844. @td.skip_if_no("lxml")
  845. def test_incorrect_xsl_syntax():
  846. from lxml.etree import XMLSyntaxError
  847. xsl = """\
  848. <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  849. <xsl:output method="xml" encoding="utf-8" indent="yes" >
  850. <xsl:strip-space elements="*"/>
  851. <xsl:template match="@*|node()">
  852. <xsl:copy>
  853. <xsl:apply-templates select="@*|node()"/>
  854. </xsl:copy>
  855. </xsl:template>
  856. <xsl:template match="row/*">
  857. <field>
  858. <xsl:attribute name="field">
  859. <xsl:value-of select="name()"/>
  860. </xsl:attribute>
  861. <xsl:value-of select="text()"/>
  862. </field>
  863. </xsl:template>
  864. </xsl:stylesheet>"""
  865. with pytest.raises(XMLSyntaxError, match=("Opening and ending tag mismatch")):
  866. geom_df.to_xml(stylesheet=xsl)
  867. @td.skip_if_no("lxml")
  868. def test_incorrect_xsl_eval():
  869. from lxml.etree import XSLTParseError
  870. xsl = """\
  871. <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  872. <xsl:output method="xml" encoding="utf-8" indent="yes" />
  873. <xsl:strip-space elements="*"/>
  874. <xsl:template match="@*|node(*)">
  875. <xsl:copy>
  876. <xsl:apply-templates select="@*|node()"/>
  877. </xsl:copy>
  878. </xsl:template>
  879. <xsl:template match="row/*">
  880. <field>
  881. <xsl:attribute name="field">
  882. <xsl:value-of select="name()"/>
  883. </xsl:attribute>
  884. <xsl:value-of select="text()"/>
  885. </field>
  886. </xsl:template>
  887. </xsl:stylesheet>"""
  888. with pytest.raises(XSLTParseError, match=("failed to compile")):
  889. geom_df.to_xml(stylesheet=xsl)
  890. @td.skip_if_no("lxml")
  891. def test_incorrect_xsl_apply():
  892. from lxml.etree import XSLTApplyError
  893. xsl = """\
  894. <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  895. <xsl:output method="xml" encoding="utf-8" indent="yes" />
  896. <xsl:strip-space elements="*"/>
  897. <xsl:template match="@*|node()">
  898. <xsl:copy>
  899. <xsl:copy-of select="document('non_existent.xml')/*"/>
  900. </xsl:copy>
  901. </xsl:template>
  902. </xsl:stylesheet>"""
  903. with pytest.raises(XSLTApplyError, match=("Cannot resolve URI")):
  904. with tm.ensure_clean("test.xml") as path:
  905. geom_df.to_xml(path, stylesheet=xsl)
  906. def test_stylesheet_with_etree():
  907. xsl = """\
  908. <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  909. <xsl:output method="xml" encoding="utf-8" indent="yes" />
  910. <xsl:strip-space elements="*"/>
  911. <xsl:template match="@*|node(*)">
  912. <xsl:copy>
  913. <xsl:apply-templates select="@*|node()"/>
  914. </xsl:copy>
  915. </xsl:template>"""
  916. with pytest.raises(
  917. ValueError, match=("To use stylesheet, you need lxml installed")
  918. ):
  919. geom_df.to_xml(parser="etree", stylesheet=xsl)
  920. @td.skip_if_no("lxml")
  921. def test_style_to_csv():
  922. xsl = """\
  923. <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  924. <xsl:output method="text" indent="yes" />
  925. <xsl:strip-space elements="*"/>
  926. <xsl:param name="delim">,</xsl:param>
  927. <xsl:template match="/data">
  928. <xsl:text>,shape,degrees,sides&#xa;</xsl:text>
  929. <xsl:apply-templates select="row"/>
  930. </xsl:template>
  931. <xsl:template match="row">
  932. <xsl:value-of select="concat(index, $delim, shape, $delim,
  933. degrees, $delim, sides)"/>
  934. <xsl:text>&#xa;</xsl:text>
  935. </xsl:template>
  936. </xsl:stylesheet>"""
  937. out_csv = geom_df.to_csv(lineterminator="\n")
  938. if out_csv is not None:
  939. out_csv = out_csv.strip()
  940. out_xml = geom_df.to_xml(stylesheet=xsl)
  941. assert out_csv == out_xml
  942. @td.skip_if_no("lxml")
  943. def test_style_to_string():
  944. xsl = """\
  945. <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  946. <xsl:output method="text" indent="yes" />
  947. <xsl:strip-space elements="*"/>
  948. <xsl:param name="delim"><xsl:text> </xsl:text></xsl:param>
  949. <xsl:template match="/data">
  950. <xsl:text> shape degrees sides&#xa;</xsl:text>
  951. <xsl:apply-templates select="row"/>
  952. </xsl:template>
  953. <xsl:template match="row">
  954. <xsl:value-of select="concat(index, ' ',
  955. substring($delim, 1, string-length('triangle')
  956. - string-length(shape) + 1),
  957. shape,
  958. substring($delim, 1, string-length(name(degrees))
  959. - string-length(degrees) + 2),
  960. degrees,
  961. substring($delim, 1, string-length(name(sides))
  962. - string-length(sides) + 2),
  963. sides)"/>
  964. <xsl:text>&#xa;</xsl:text>
  965. </xsl:template>
  966. </xsl:stylesheet>"""
  967. out_str = geom_df.to_string()
  968. out_xml = geom_df.to_xml(na_rep="NaN", stylesheet=xsl)
  969. assert out_xml == out_str
  970. @td.skip_if_no("lxml")
  971. def test_style_to_json():
  972. xsl = """\
  973. <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  974. <xsl:output method="text" indent="yes" />
  975. <xsl:strip-space elements="*"/>
  976. <xsl:param name="quot">"</xsl:param>
  977. <xsl:template match="/data">
  978. <xsl:text>{"shape":{</xsl:text>
  979. <xsl:apply-templates select="descendant::row/shape"/>
  980. <xsl:text>},"degrees":{</xsl:text>
  981. <xsl:apply-templates select="descendant::row/degrees"/>
  982. <xsl:text>},"sides":{</xsl:text>
  983. <xsl:apply-templates select="descendant::row/sides"/>
  984. <xsl:text>}}</xsl:text>
  985. </xsl:template>
  986. <xsl:template match="shape|degrees|sides">
  987. <xsl:variable name="val">
  988. <xsl:if test = ".=''">
  989. <xsl:value-of select="'null'"/>
  990. </xsl:if>
  991. <xsl:if test = "number(text()) = text()">
  992. <xsl:value-of select="text()"/>
  993. </xsl:if>
  994. <xsl:if test = "number(text()) != text()">
  995. <xsl:value-of select="concat($quot, text(), $quot)"/>
  996. </xsl:if>
  997. </xsl:variable>
  998. <xsl:value-of select="concat($quot, preceding-sibling::index,
  999. $quot,':', $val)"/>
  1000. <xsl:if test="preceding-sibling::index != //row[last()]/index">
  1001. <xsl:text>,</xsl:text>
  1002. </xsl:if>
  1003. </xsl:template>
  1004. </xsl:stylesheet>"""
  1005. out_json = geom_df.to_json()
  1006. out_xml = geom_df.to_xml(stylesheet=xsl)
  1007. assert out_json == out_xml
  1008. # COMPRESSION
  1009. geom_xml = """\
  1010. <?xml version='1.0' encoding='utf-8'?>
  1011. <data>
  1012. <row>
  1013. <index>0</index>
  1014. <shape>square</shape>
  1015. <degrees>360</degrees>
  1016. <sides>4.0</sides>
  1017. </row>
  1018. <row>
  1019. <index>1</index>
  1020. <shape>circle</shape>
  1021. <degrees>360</degrees>
  1022. <sides/>
  1023. </row>
  1024. <row>
  1025. <index>2</index>
  1026. <shape>triangle</shape>
  1027. <degrees>180</degrees>
  1028. <sides>3.0</sides>
  1029. </row>
  1030. </data>"""
  1031. def test_compression_output(parser, compression_only):
  1032. with tm.ensure_clean() as path:
  1033. geom_df.to_xml(path, parser=parser, compression=compression_only)
  1034. with get_handle(
  1035. path,
  1036. "r",
  1037. compression=compression_only,
  1038. ) as handle_obj:
  1039. output = handle_obj.handle.read()
  1040. output = equalize_decl(output)
  1041. assert geom_xml == output.strip()
  1042. def test_filename_and_suffix_comp(parser, compression_only):
  1043. compfile = "xml." + _compression_to_extension[compression_only]
  1044. with tm.ensure_clean(filename=compfile) as path:
  1045. geom_df.to_xml(path, parser=parser, compression=compression_only)
  1046. with get_handle(
  1047. path,
  1048. "r",
  1049. compression=compression_only,
  1050. ) as handle_obj:
  1051. output = handle_obj.handle.read()
  1052. output = equalize_decl(output)
  1053. assert geom_xml == output.strip()
  1054. def test_ea_dtypes(any_numeric_ea_dtype, parser):
  1055. # GH#43903
  1056. expected = """<?xml version='1.0' encoding='utf-8'?>
  1057. <data>
  1058. <row>
  1059. <index>0</index>
  1060. <a/>
  1061. </row>
  1062. </data>"""
  1063. df = DataFrame({"a": [NA]}).astype(any_numeric_ea_dtype)
  1064. result = df.to_xml(parser=parser)
  1065. assert equalize_decl(result).strip() == expected
  1066. def test_unsuported_compression(parser):
  1067. with pytest.raises(ValueError, match="Unrecognized compression type"):
  1068. with tm.ensure_clean() as path:
  1069. geom_df.to_xml(path, parser=parser, compression="7z")
  1070. # STORAGE OPTIONS
  1071. @pytest.mark.single_cpu
  1072. @td.skip_if_no("s3fs")
  1073. @td.skip_if_no("lxml")
  1074. def test_s3_permission_output(parser, s3_resource):
  1075. # s3_resource hosts pandas-test
  1076. import s3fs
  1077. with pytest.raises(PermissionError, match="Access Denied"):
  1078. fs = s3fs.S3FileSystem(anon=True)
  1079. fs.ls("pandas-test")
  1080. geom_df.to_xml("s3://pandas-test/geom.xml", compression="zip", parser=parser)