0

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?

2
  • Transforming xml can be best done by xslt. It is designed for that. See this answer on how to do that using python: stackoverflow.com/a/51972482/3710053 Commented Sep 22, 2023 at 7:34
  • Add an empty namespace, find an example here. Commented Sep 22, 2023 at 16:56

1 Answer 1

0

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.