mvantellingen / python-zeep

A Python SOAP client
http://docs.python-zeep.org
Other
1.88k stars 586 forks source link

[question] How to render datastructure instances as XML? #1223

Open sanjioh opened 3 years ago

sanjioh commented 3 years ago

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!

grakic commented 3 years ago
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)
sanjioh commented 3 years ago

@grakic Thanks, it works perfectly!