Skip to content

Commit

Permalink
Merge pull request #1258 from effigies/enh/xml-kwargs
Browse files Browse the repository at this point in the history
ENH: Permit XmlSerializable.to_xml() to pass kwargs to ElementTree.tostring()
  • Loading branch information
effigies authored Oct 18, 2023
2 parents adcc9ba + cea2f6c commit e356408
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 12 deletions.
4 changes: 2 additions & 2 deletions nibabel/gifti/gifti.py
Original file line number Diff line number Diff line change
Expand Up @@ -852,7 +852,7 @@ def _to_xml_element(self):
GIFTI.append(dar._to_xml_element())
return GIFTI

def to_xml(self, enc='utf-8', *, mode='strict') -> bytes:
def to_xml(self, enc='utf-8', *, mode='strict', **kwargs) -> bytes:
"""Return XML corresponding to image content"""
if mode == 'strict':
if any(arr.datatype not in GIFTI_DTYPES for arr in self.darrays):
Expand Down Expand Up @@ -882,7 +882,7 @@ def to_xml(self, enc='utf-8', *, mode='strict') -> bytes:
header = b"""<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE GIFTI SYSTEM "http://www.nitrc.org/frs/download.php/115/gifti.dtd">
"""
return header + super().to_xml(enc)
return header + super().to_xml(enc, **kwargs)

# Avoid the indirection of going through to_file_map
def to_bytes(self, enc='utf-8', *, mode='strict'):
Expand Down
27 changes: 17 additions & 10 deletions nibabel/xmlutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,24 @@


class XmlSerializable:
"""Basic interface for serializing an object to xml"""
"""Basic interface for serializing an object to XML"""

def _to_xml_element(self):
def _to_xml_element(self) -> Element:
"""Output should be a xml.etree.ElementTree.Element"""
raise NotImplementedError()
raise NotImplementedError # pragma: no cover

def to_xml(self, enc='utf-8'):
"""Output should be an xml string with the given encoding.
(default: utf-8)"""
def to_xml(self, enc='utf-8', **kwargs) -> bytes:
r"""Generate an XML bytestring with a given encoding.
Parameters
----------
enc : :class:`string`
Encoding to use for the generated bytestring. Default: 'utf-8'
\*\*kwargs : :class:`dict`
Additional keyword arguments to :func:`xml.etree.ElementTree.tostring`.
"""
ele = self._to_xml_element()
return '' if ele is None else tostring(ele, enc)
return b'' if ele is None else tostring(ele, enc, **kwargs)


class XmlBasedHeader(FileBasedHeader, XmlSerializable):
Expand Down Expand Up @@ -101,10 +108,10 @@ def parse(self, string=None, fname=None, fptr=None):
parser.ParseFile(fptr)

def StartElementHandler(self, name, attrs):
raise NotImplementedError
raise NotImplementedError # pragma: no cover

def EndElementHandler(self, name):
raise NotImplementedError
raise NotImplementedError # pragma: no cover

def CharacterDataHandler(self, data):
raise NotImplementedError
raise NotImplementedError # pragma: no cover

0 comments on commit e356408

Please sign in to comment.