BeautifulSoup prettify() modifies significant whitespace even if the attribute xml:space is set to "preserve". Example xml file with significant whitespace: <svg viewBox="0 0 160 50" xmlns="http://www.w3.org/2000/svg"> <text y="20" xml:space="default"> Default spacing</text> <text y="40" xml:space="preserve"> <tspan>reserved spacing</tspan></text> </svg> Code: from bs4 import BeautifulSoup xml_string_with_significant_whitespace =''' <svg viewBox="0 0 160 50" xmlns="http://www.w3.org/2000/svg"> <text y="20" xml:space="default"> Default spacing</text> <text y="40" xml:space="preserve"> <tspan>reserved spacing</tspan></text> </svg> ''' soup = BeautifulSoup(xml_string_with_significant_whitespace, "xml") # no modifications made print(soup.prettify()) # modifies significant whitespace # print(str(soup)) # doesn't modify significant whitespace Output: <svg viewBox="0 0 160 50" xmlns="http://www.w3.org/2000/svg"> <text xml:space="default" y="20"> Default spacing </text> <text xml:space="preserve" y="40"> <tspan> reserved spacing </tspan> </text> </svg> Text will be moved due to modified whitespace. How do I prevent prettify() from changing the meaning of the xml file and not just the layout? Edit: Made the question more focused to prevent closing of the question. (An earlier version of this post also asked about how to prevent namespaces from being added by BeautifulSoup. This was caused by the attribute xmlns:svg="http://www.w3.org/2000/svg. Some other xml libraries do not add namespace.) Continue reading...