I have this xml file located at path "C:\Program Files (x86)\Microsoft SQL Server\100\Setup Bootstrap\Log\20210331_124249\Datastore_GlobalRules\Datastore_Discovery.xml", it is a one-line-only xml file, you can view it here.
It is pretty ugly and not very readable and hard to get information from it, so I Google searched for a method to beautify the xml file with Python, and I found this question:Pretty printing XML in Python
The first two answers didn't give me what I wanted, the printed xml is still ugly, but the third answer did give me what wanted:
from xml.etree import ElementTree
def indent(elem, level=0):
i = "\n" + level*" "
j = "\n" + (level-1)*" "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + " "
if not elem.tail or not elem.tail.strip():
elem.tail = i
for subelem in elem:
indent(subelem, level+1)
if not elem.tail or not elem.tail.strip():
elem.tail = j
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = j
return elem
xml = ElementTree.parse('C:/Program Files (x86)/Microsoft SQL Server/100/Setup Bootstrap/Log/20210331_124249/Datastore_GlobalRules/Datastore_Discovery.xml').getroot()
indent(xml)
ElementTree.dump(xml)
This is the output: output.xml
However I can't redirect the output to an xml file;
I first tried to use this method:
out = open('C:/Output.xml','w')
out.write(ElementTree.dump(xml))
out.close()
It gave this error:
TypeError: write() argument must be str, not None
Tried this:
xml.write('C:/output.xml')
It gave this error:
AttributeError: 'xml.etree.ElementTree.Element' object has no attribute 'write'
If I use this:
ElementTree.dump(xml).write('C:/output.xml')
Results this error:
AttributeError: 'NoneType' object has no attribute 'write'
How can I redirect the output of ElementTree.dump(xml) to an xml file? I am sorry if this question is too trivial but I am very new to Python, I don't know much, how can I do this? Any help is truly appreciated.
P.S. About how I got the output file, I copy-pasted the output from the console window.