Converting a Python object To XML without namespaces

234 Views Asked by At

I am using the XmlSerializer from xsdata to convert a python3.9 dataclass object into XML.

This is the code

# create serializer
XML_SERIALIZER = XmlSerializer(config=SerializerConfig(xml_declaration=False))

# initialize class with multiple properties
my_obj = MyDataClass(prop1='some val', prop2='some val' , , ,)    

# serialize object
serialized_value = XML_SERIALIZER.render(my_obj)

This generates an xml representation of the object but with things I don't want in the xml like this xmlns... xsi:type

 <SomeProperty xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="SomeTypePropetryInMyDataClass">
  <code>
   XYZ
  </code>
 </SomeProperty>

I tried render like this too XML_SERIALIZER.render(my_obj, ns_map=None), but that didn't work either.

Does anyone know how to render that without the namespaces and type information added? Is there another XML serializer/deserializer for python that is more flexible?

1

There are 1 best solutions below

0
balderman On BEST ANSWER

Here you go:

(The flow is: dataclass --> dict --> xml)

import dataclasses
import dicttoxml


@dataclasses.dataclass
class MyData:
    x: int
    name: str
    friends: list[str]


data: MyData = MyData(9, 'jack', ['ben', 'sam'])
print(data)
data_as_dict: dict = dataclasses.asdict(data)
print(data_as_dict)
xml: str = dicttoxml.dicttoxml(data_as_dict, attr_type=False).decode()
print(xml)

output

MyData(x=9, name='jack', friends=['ben', 'sam'])
{'x': 9, 'name': 'jack', 'friends': ['ben', 'sam']}
<?xml version="1.0" encoding="UTF-8"?>
<root>
   <x>9</x>
   <name>jack</name>
   <friends>
      <item>ben</item>
      <item>sam</item>
   </friends>
</root>