Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting the right indentation of an XML file

After sending a request to an url using python and the library requests, i am writing the output in an xml file just like this:

export = s.post(url, params=params)
soup = BeautifulSoup(export.text, features='xml')

with open('exit.xml', 'wb') as f_out:  
     f_out.write(soup.encode('utf-8'))

But as an output in my xml file, i’m getting something like this :

<complex>
<real>4.4E+12</real>
<imaginary>5.4E-11</imaginary>
</complex>

With no indentation at all ! the ouput i expected would be something more like this :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<complex>
  <real>4.4E+12</real>
  <imaginary>5.4E-11</imaginary>
</complex>

so i read about xmlformatter and tried :

import xmlformatter

formatter = xmlformatter.Formatter(indent="1", indent_char="\t", encoding_output="ISO-8859-1", 
preserve=["literal"])
formatter.format_file("exit.xml")

But it didn’t work. Maybe indentation is not needed but i’m also asking this for my personal knowledge. Any ideas or help would be very appreciated!

>Solution :

Pretty printing XML in Python

XML as a file format doesn’t need to be indented, and so the lib does’t bother. However, if you want to "pretty print" your xml, see the link above.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading