【问题标题】:How to Pretty Print XML returned from Requests lib in python如何漂亮地打印从 Python 中的请求库返回的 XML
【发布时间】:2016-06-17 20:29:45
【问题描述】:

我正在使用“请求”库来运行 SOAP 服务。

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

响应如下(未格式化)

<?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>

我如何漂亮地打印这个?

【问题讨论】:

    标签: xml web-services soap python-requests pretty-print


    【解决方案1】:

    您可以使用 beautifulsoup 传递 "xml" 作为解析器:

    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())
    

    输出:

    <?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>
    

    【讨论】:

      【解决方案2】:

      假设您从 xml 字符串开始:

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

      #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()
      

      【讨论】:

        猜你喜欢
        • 2017-12-19
        • 2010-09-13
        • 1970-01-01
        • 1970-01-01
        • 2014-05-21
        • 2012-03-25
        相关资源
        最近更新 更多