0

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 :

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

clemdcz
  • 99
  • 7
  • Have you looked into [PyTidyLib](https://pypi.org/project/pytidylib/)? I've used [HTML Tidy](https://www.html-tidy.org/) countless times to clean up ugly HTML. It's suppsoed to work on XML too. – MDeBusk Oct 12 '22 at 15:11

1 Answers1

-1

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.

Eric Yang
  • 2,678
  • 1
  • 12
  • 18