简体   繁体   中英

Indent xml data fetched via request | python |

I got stuck not getting how to achieve it.

Need your suggestion on this how to implement in my code

My code :

import requests

url = '....'  # not mentioning as its private 

headers_details = {
'Host' : 'axb.vttp.com',
'Accept-Encoding' : 'gzip,deflate',
'Accept' : '*/*'
}

parameter = { 'id' : '4566' ,'key' :'tyuo' }

rq = requests.post( url,params=parameter, headers=headers_details) 

with open('demo.xml','w') as wr:
    wr.write(rq.content)

My data is written to my xml file. But its not in indent format the xml data.

How to achieve the xml data in file in proper indentation format

You've need to parse the xml, then serialise it with indentation.

With lxml :

from lxml import etree
import requests

url = r"https://www.w3schools.com/xml/note.xml"

rq = requests.get(url)

# Parse the xml
root = etree.fromstring(rq.content)

with open('demo.xml', 'wb') as wr:
    # Serialise the xml
    wr.write(etree.tostring(root, encoding="utf-8", pretty_print=True))

See:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM