python-zeep icon indicating copy to clipboard operation
python-zeep copied to clipboard

[question] How to render datastructure instances as XML?

Open sanjioh opened this issue 3 years ago • 2 comments

Hi,

I need to get the XML representation of instances of (nested) complex types. I get to the point of creating the relevant objects:

from zeep import Client

client = Client('http://my-soap-service.example.com?wsdl')
person_type = client.get_type('Person')
print(person_type)
# Person(Person(Name: xsd:string, LastName: xsd:string))
person = person_type(Name='John', LastName='Doe')
print(person)
# {
#    'Name': 'John',
#    'LastName': 'Doe'
# }

What I'd like to do now is getting XML out of the person instance, ideally by invoking a method that returns an instance of xml.etree.ElementTree.Element (or lxml's equivalent):

from xml.etree.ElementTree import tostring

element = person.as_xml()  # as_xml() does not exist of course
xml = tostring(element)
print(xml)
# b'<Person><Name>John</Name><LastName>Doe</LastName></Person>'

Is there some way to get this?

Thanks!

sanjioh avatar May 06 '21 11:05 sanjioh

from zeep import Client
from xml.etree import ElementTree

client = Client('http://my-soap-service.example.com?wsdl')
person_type = client.get_type('Person')

person = person_type(Name='John', LastName='Doe')
person_node = ElementTree.Element('Person')
person_type.render(person_node, person)
ElementTree.tostring(person_node)

# or
person_node = ElementTree.Element('Person')
person_type.render(person_node, {
  "Name": "John",
  "LastName": "Doe",
})
ElementTree.tostring(person_node)

grakic avatar Jun 07 '21 01:06 grakic

@grakic Thanks, it works perfectly!

sanjioh avatar Jun 07 '21 06:06 sanjioh