Source code for json2xml.json2xml

from typing import Any

__lazy_modules__ = ["defusedxml.minidom", "pyexpat"]

from . import dicttoxml_fast as dicttoxml
from .types import JSONValue
from .utils import InvalidDataError


# @lat: [[architecture#Core pipeline]]
[docs] class Json2xml: """ Wrapper class to convert the data to xml """ def __init__( self, data: JSONValue = None, wrapper: str = "all", root: bool = True, pretty: bool = True, attr_type: bool = True, item_wrap: bool = True, xpath_format: bool = False, cdata: bool = False, list_headers: bool = False, ): self.data = data self.pretty = pretty self.wrapper = wrapper self.attr_type = attr_type self.root = root self.item_wrap = item_wrap self.xpath_format = xpath_format self.cdata = cdata self.list_headers = list_headers # @lat: [[behavior#Conversion output]] # @lat: [[behavior#Invalid XML payloads]]
[docs] def to_xml(self) -> Any | None: """ Convert to xml using dicttoxml.dicttoxml and then pretty print it. """ if self.data is not None: xml_data = dicttoxml.dicttoxml( self.data, root=self.root, custom_root=self.wrapper, attr_type=self.attr_type, item_wrap=self.item_wrap, xpath_format=self.xpath_format, cdata=self.cdata, list_headers=self.list_headers, ) if self.pretty: from pyexpat import ExpatError from defusedxml.minidom import parseString try: result = parseString(xml_data.decode("utf-8")).toprettyxml(encoding="UTF-8").decode() except ExpatError: raise InvalidDataError return result return xml_data return None