kiric8494
kiric8494

Reputation: 205

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

Upvotes: 0

Views: 165

Answers (1)

GordonAitchJay
GordonAitchJay

Reputation: 4880

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:

Upvotes: 1

Related Questions