Convert string to XML object

Asked

Viewed 152 times

-1

I am consuming a SOAP Web Service and I can call through Python using the module zeep.

client = Client(wsdl='meu_endpoint?WSDL')

print(client.service.ObterDividaAtivaPorCPF('user','senha','cpf'))

It returns a string in this format:

inserir a descrição da imagem aqui

How do I convert this string into an XML object so I can parse it? I would like to fetch the value of a certain tag.

1 answer

0

You can import the library xml.etree.ElementTree and with it to parse and read the XML data.


To parse, you can use the method fromstring, to find a tag, use the method find in the XML object, below is a very simple use example:

import xml.etree.ElementTree as ET

#Exemplo de XML qualquer
xml =  '<?xml version="1.0" encoding="UTF-8"?>'
xml += ' <note>'
xml += '  <to>Alguém</to>'
xml += '  <from>De outra pessoa</from>'
xml += '  <heading>Recado</heading>'
xml += '  <body>Não esqueça...</body>'
xml += ' </note>'

#Efetuar o parser do XML
tree = ET.fromstring(xml)

#Exibe o conteúdo do elemento body
print(tree.find("body").text)

The method find returns None if you do not find the element.


See this online example: https://repl.it/repls/HungryPaltrySyndrome

Documentation: https://docs.python.org/3/library/xml.etree.elementtree.html

  • What I’m not getting is to take the call back to the Web Service and turn it into an XML. I haven’t found any way to make the return itself already come in XML format (according to your great example).

  • Can you call and return WS? The return is currently a string?

  • Yes, the return is a string. I confirm this using the type function that returns str.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.