2016-06-17 2 views
0

J'utilise la bibliothèque "requests" pour exécuter des services SOAP.Comment Pretty Print XML renvoyé à partir de Requests lib en python

headers = {'content-type': 'application/json'} 
response = requests.post(test_url,data=testData.request_body,headers=headers) 

la réponse vient comme ci-dessous (non formaté)

<?xml version="1.0" encoding="UTF-8"?> 
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="https://xxx.abc.in"><SOAP-ENV:Body><ns1:LoginResponse><return><SessionID>abc12345</SessionID><ResponseCode>0</ResponseCode><ResponseMessage>Successful</ResponseMessage></return></ns1:LoginResponse></SOAP-ENV:Body></SOAP-ENV:Envelope> 

Comment puis-je imprimer ce joli?

Répondre

0

Vous pouvez utiliser beautifulsoup passant "xml" comme l'analyseur:

x = '''<?xml version="1.0" encoding="UTF-8"?> 
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="https://xxx.abc.in"><SOAP-ENV:Body><ns1:LoginResponse><return><SessionID>abc12345</SessionID><ResponseCode>0</ResponseCode><ResponseMessage>Successful</ResponseMessage></return></ns1:LoginResponse></SOAP-ENV:Body></SOAP-ENV:Envelope>''' 

print(BeautifulSoup(x, "xml").prettify()) 

Sortie:

<?xml version="1.0" encoding="utf-8"?> 
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="https://xxx.abc.in"> 
<SOAP-ENV:Body> 
    <ns1:LoginResponse> 
    <return> 
    <SessionID> 
    abc12345 
    </SessionID> 
    <ResponseCode> 
    0 
    </ResponseCode> 
    <ResponseMessage> 
    Successful 
    </ResponseMessage> 
    </return> 
    </ns1:LoginResponse> 
</SOAP-ENV:Body> 
</SOAP-ENV:Envelope> 
+0

Merci! Cela fonctionne – RJX

+0

@RJX Marquer la réponse comme acceptée. – Salman

0

En supposant que vous êtes à partir de la chaîne xml:

#LXML 
from lxml import etree 
xmlRootNode = etree.fromstring(resp_str) 
xmlstr = etree.tostring(xmlRootNode, xml_declaration=True, encoding="UTF-8", pretty_print=True) 

ou

#xml 
import xml.etree.ElementTree as ET 
import xml.dom.minidom 
s = ET.tostring(xmlRootNode, encoding="UTF-8", method="xml") 
xmln = xml.dom.minidom.parseString(resp_str) 
xmlstr = xmln.toprettyxml()