可以使用Spyne库将Python字典/JSON转换为XML。下面是一个使用Spyne的示例代码:
from spyne import Application, rpc, ServiceBase, Iterable, Integer, Unicode
from spyne.protocol.soap import Soap11
from spyne.server.wsgi import WsgiApplication
from spyne.util.xml import get_xml_as_dict
# 定义一个Spyne服务
class MyService(ServiceBase):
@rpc(Unicode, _returns=Unicode)
def xml_to_dict(ctx, xml):
# 将XML转换为Python字典
data_dict = get_xml_as_dict(xml)
# 将字典转换为JSON字符串
import json
json_str = json.dumps(data_dict)
return json_str
# 创建一个Spyne应用程序
soap_app = Application(
[MyService],
tns='spyne.examples.hello',
in_protocol=Soap11(validator='lxml'),
out_protocol=Soap11()
)
# 创建一个WSGI应用程序
wsgi_app = WsgiApplication(soap_app)
# 启动服务器
if __name__ == '__main__':
from wsgiref.simple_server import make_server
server = make_server('localhost', 8000, wsgi_app)
server.serve_forever()
使用上述代码,你可以将XML转换为Python字典,然后再将字典转换为JSON字符串。