user10185274
user10185274

Reputation: 35

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

Here is the code but the exported xml appears badly formatted.

import xml.etree.ElementTree as ET
import os

sampleXML = """<?xml version="1.0" encoding="ASCII"?>
    <Metadata version="1.0">
        <CODE_OK>510</CODE_OK>
        <DeliveryDate>13/08/2018</DeliveryDate>
    </Metadata>
    """

tree = ET.ElementTree(ET.fromstring(sampleXML))
for folder in os.listdir("YourPath"):         #Iterate the dir
    tree.find("CODE_OK").text = folder        #Update dir name in XML
    tree.write(open(os.path.join(r"Path", folder, "newxml.xml"), "wb")) #Write to XML

How to make the exported xml appear normally formatted?

Upvotes: 1

Views: 1369

Answers (1)

RobJan
RobJan

Reputation: 1441

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"))

Upvotes: 1

Related Questions