Skip to content

REF: Deduplicate to_xml code #45132

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Jan 1, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
137 changes: 41 additions & 96 deletions pandas/io/formats/xml.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ def __init__(
self,
frame: DataFrame,
path_or_buffer: FilePath | WriteBuffer[bytes] | None = None,
index: bool | None = True,
index: bool = True,
root_name: str | None = "data",
row_name: str | None = "row",
na_rep: str | None = None,
Expand Down Expand Up @@ -189,8 +189,8 @@ def process_dataframe(self) -> dict[int | str, dict[str, Any]]:
if self.index:
df = df.reset_index()

if self.na_rep:
df = df.replace({None: self.na_rep, float("nan"): self.na_rep})
if self.na_rep is not None:
df = df.fillna(self.na_rep)

return df.to_dict(orient="index")

Expand Down Expand Up @@ -255,7 +255,27 @@ def build_attribs(self) -> None:
works with tuples for multindex or hierarchical columns.
"""

raise AbstractMethodError(self)
if not self.attr_cols:
return

for col in self.attr_cols:
attr_name = self._get_flat_col_name(col)
try:
val = None if isna(self.d[col]) else str(self.d[col])
if val is not None:
self.elem_row.attrib[attr_name] = val
except KeyError:
raise KeyError(f"no valid column, {col}")

def _get_flat_col_name(self, col: str | tuple) -> str:
flat_col = col
if isinstance(col, tuple):
flat_col = (
"".join([str(c) for c in col]).strip()
if "" in col
else "_".join([str(c) for c in col]).strip()
)
return f"{self.prefix_uri}{flat_col}"

def build_elems(self) -> None:
"""
Expand All @@ -267,6 +287,21 @@ def build_elems(self) -> None:

raise AbstractMethodError(self)

def _build_elems(self, sub_element_cls) -> None:

if not self.elem_cols:
return

for col in self.elem_cols:
elem_name = self._get_flat_col_name(col)
try:
val = (
None if isna(self.d[col]) or self.d[col] == "" else str(self.d[col])
)
sub_element_cls(self.elem_row, elem_name).text = val
except KeyError:
raise KeyError(f"no valid column, {col}")

def write_output(self) -> str | None:
xml_doc = self.build_tree()

Expand Down Expand Up @@ -357,56 +392,10 @@ def get_prefix_uri(self) -> str:

return uri

def build_attribs(self) -> None:
if not self.attr_cols:
return

for col in self.attr_cols:
flat_col = col
if isinstance(col, tuple):
flat_col = (
"".join([str(c) for c in col]).strip()
if "" in col
else "_".join([str(c) for c in col]).strip()
)

attr_name = f"{self.prefix_uri}{flat_col}"
try:
val = (
None
if self.d[col] is None or self.d[col] != self.d[col]
else str(self.d[col])
)
if val is not None:
self.elem_row.attrib[attr_name] = val
except KeyError:
raise KeyError(f"no valid column, {col}")

def build_elems(self) -> None:
from xml.etree.ElementTree import SubElement

if not self.elem_cols:
return

for col in self.elem_cols:
flat_col = col
if isinstance(col, tuple):
flat_col = (
"".join([str(c) for c in col]).strip()
if "" in col
else "_".join([str(c) for c in col]).strip()
)

elem_name = f"{self.prefix_uri}{flat_col}"
try:
val = (
None
if self.d[col] in [None, ""] or self.d[col] != self.d[col]
else str(self.d[col])
)
SubElement(self.elem_row, elem_name).text = val
except KeyError:
raise KeyError(f"no valid column, {col}")
self._build_elems(SubElement)

def prettify_tree(self) -> bytes:
"""
Expand Down Expand Up @@ -529,54 +518,10 @@ def get_prefix_uri(self) -> str:

return uri

def build_attribs(self) -> None:
if not self.attr_cols:
return

for col in self.attr_cols:
flat_col = col
if isinstance(col, tuple):
flat_col = (
"".join([str(c) for c in col]).strip()
if "" in col
else "_".join([str(c) for c in col]).strip()
)

attr_name = f"{self.prefix_uri}{flat_col}"
try:
val = (
None
if self.d[col] is None or self.d[col] != self.d[col]
else str(self.d[col])
)
if val is not None:
self.elem_row.attrib[attr_name] = val
except KeyError:
raise KeyError(f"no valid column, {col}")

def build_elems(self) -> None:
from lxml.etree import SubElement

if not self.elem_cols:
return

for col in self.elem_cols:
flat_col = col
if isinstance(col, tuple):
flat_col = (
"".join([str(c) for c in col]).strip()
if "" in col
else "_".join([str(c) for c in col]).strip()
)

elem_name = f"{self.prefix_uri}{flat_col}"
try:
val = (
None if isna(self.d[col]) or self.d[col] == "" else str(self.d[col])
)
SubElement(self.elem_row, elem_name).text = val
except KeyError:
raise KeyError(f"no valid column, {col}")
self._build_elems(SubElement)

def transform_doc(self) -> bytes:
"""
Expand Down
6 changes: 3 additions & 3 deletions pandas/tests/io/xml/test_to_xml.py
Original file line number Diff line number Diff line change
Expand Up @@ -1309,7 +1309,7 @@ def test_filename_and_suffix_comp(parser, compression_only):


@td.skip_if_no("lxml")
def test_ea_dtypes(any_numeric_ea_dtype):
def test_ea_dtypes(any_numeric_ea_dtype, parser):
# GH#43903
expected = """<?xml version='1.0' encoding='utf-8'?>
<data>
Expand All @@ -1319,8 +1319,8 @@ def test_ea_dtypes(any_numeric_ea_dtype):
</row>
</data>"""
df = DataFrame({"a": [NA]}).astype(any_numeric_ea_dtype)
result = df.to_xml()
assert result.strip() == expected
result = df.to_xml(parser=parser)
assert equalize_decl(result).strip() == expected


def test_unsuported_compression(datapath, parser):
Expand Down