Exported xml isn't well formatted but appears in one line?

怎甘沉沦 提交于 2019-12-02 12:44:26

I found in docs that xml module has an implementation of Document Object Model interface. I provide a simple example

from xml.dom.minidom import parseString

example = parseString(sampleXML) # your string

# write to file
with open('file.xml', 'w') as file:
    example.writexml(file, indent='\n', addindent=' ')

Output:

<?xml version="1.0" ?>
<Metadata version="1.0">


 <CODE_OK>510</CODE_OK>


 <DeliveryDate>13/08/2018</DeliveryDate>


</Metadata>

Update

You can also write like this

example = parseString(sampleXML).toprettyxml()
with open('file.xml', 'w') as file:
    file.write(example)

Output:

<?xml version="1.0" ?>
<Metadata version="1.0">


    <CODE_OK>510</CODE_OK>


    <DeliveryDate>13/08/2018</DeliveryDate>


</Metadata>

Update 2

I copy all your code and only add indent from this site. And for me is working correctly

import xml.etree.ElementTree as ET
import os

sampleXML = "your xml"
tree = ET.ElementTree(ET.fromstring(sampleXML))

indent(tree.getroot()) # this I add

for folder in os.listdir(path):
    tree.find("CODE_OK").text = folder
    tree.write(open(os.path.join(path, folder, "newxml.xml"), "wb"))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!