Skip to content

CLN: Adjust namespace handling in to_xml #54201

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 1 commit into from
Jul 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
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
58 changes: 15 additions & 43 deletions pandas/io/formats/xml.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,18 +251,11 @@ def other_namespaces(self) -> dict:
"""

nmsp_dict: dict[str, str] = {}
if self.namespaces and self.prefix is None:
nmsp_dict = {
"xmlns": n # noqa: RUF011
for p, n in self.namespaces.items()
if p != ""
}

if self.namespaces and self.prefix:
if self.namespaces:
nmsp_dict = {
"xmlns": n # noqa: RUF011
f"xmlns{p if p=='' else f':{p}'}": n
for p, n in self.namespaces.items()
if p == ""
if n != self.prefix_uri[1:-1]
}

return nmsp_dict
Expand Down Expand Up @@ -365,16 +358,16 @@ def build_tree(self) -> bytes:
elem_row = self.build_attribs(d, elem_row)
self.build_elems(d, elem_row)

self.out_xml = tostring(self.root, method="xml", encoding=self.encoding)
self.out_xml = tostring(
self.root,
method="xml",
encoding=self.encoding,
xml_declaration=self.xml_declaration,
)

if self.pretty_print:
self.out_xml = self.prettify_tree()

if self.xml_declaration:
self.out_xml = self.add_declaration()
else:
self.out_xml = self.remove_declaration()

if self.stylesheet is not None:
raise ValueError(
"To use stylesheet, you need lxml installed and selected as parser."
Expand All @@ -395,8 +388,10 @@ def get_prefix_uri(self) -> str:
uri = f"{{{self.namespaces[self.prefix]}}}"
except KeyError:
raise KeyError(f"{self.prefix} is not included in namespaces")
else:
elif "" in self.namespaces:
uri = f'{{{self.namespaces[""]}}}'
else:
uri = ""

return uri

Expand All @@ -418,31 +413,6 @@ def prettify_tree(self) -> bytes:

return dom.toprettyxml(indent=" ", encoding=self.encoding)

def add_declaration(self) -> bytes:
"""
Add xml declaration.

This method will add xml declaration of working tree. Currently,
xml_declaration is supported in etree starting in Python 3.8.
"""
decl = f'<?xml version="1.0" encoding="{self.encoding}"?>\n'

return (
self.out_xml
if self.out_xml.startswith(b"<?xml")
else decl.encode(self.encoding) + self.out_xml
)

def remove_declaration(self) -> bytes:
"""
Remove xml declaration.

This method will remove xml declaration of working tree. Currently,
pretty_print is not supported in etree.
"""

return self.out_xml.split(b"?>")[-1].strip()


class LxmlXMLFormatter(BaseXMLFormatter):
"""
Expand Down Expand Up @@ -513,8 +483,10 @@ def get_prefix_uri(self) -> str:
uri = f"{{{self.namespaces[self.prefix]}}}"
except KeyError:
raise KeyError(f"{self.prefix} is not included in namespaces")
else:
elif "" in self.namespaces:
uri = f'{{{self.namespaces[""]}}}'
else:
uri = ""

return uri

Expand Down
43 changes: 34 additions & 9 deletions pandas/tests/io/xml/test_to_xml.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,6 @@ def equalize_decl(doc):
'<?xml version="1.0" encoding="utf-8"?',
"<?xml version='1.0' encoding='utf-8'?",
)

return doc


Expand Down Expand Up @@ -705,6 +704,39 @@ def test_default_namespace(parser, geom_df):
assert output == expected


def test_unused_namespaces(parser, geom_df):
expected = """\
<?xml version='1.0' encoding='utf-8'?>
<data xmlns:oth="http://other.org" xmlns:ex="http://example.com">
<row>
<index>0</index>
<shape>square</shape>
<degrees>360</degrees>
<sides>4.0</sides>
</row>
<row>
<index>1</index>
<shape>circle</shape>
<degrees>360</degrees>
<sides/>
</row>
<row>
<index>2</index>
<shape>triangle</shape>
<degrees>180</degrees>
<sides>3.0</sides>
</row>
</data>"""

output = geom_df.to_xml(
namespaces={"oth": "http://other.org", "ex": "http://example.com"},
parser=parser,
)
output = equalize_decl(output)

assert output == expected


# PREFIX


Expand Down Expand Up @@ -750,7 +782,7 @@ def test_missing_prefix_in_nmsp(parser, geom_df):
def test_namespace_prefix_and_default(parser, geom_df):
expected = """\
<?xml version='1.0' encoding='utf-8'?>
<doc:data xmlns="http://example.com" xmlns:doc="http://other.org">
<doc:data xmlns:doc="http://other.org" xmlns="http://example.com">
<doc:row>
<doc:index>0</doc:index>
<doc:shape>square</doc:shape>
Expand Down Expand Up @@ -778,13 +810,6 @@ def test_namespace_prefix_and_default(parser, geom_df):
)
output = equalize_decl(output)

if output is not None:
# etree and lxml differs on order of namespace prefixes
output = output.replace(
'xmlns:doc="http://other.org" xmlns="http://example.com"',
'xmlns="http://example.com" xmlns:doc="http://other.org"',
)

assert output == expected


Expand Down