D
D
Denis2015-08-18 11:13:02
Python
Denis, 2015-08-18 11:13:02

Why is xml formatting messed up when using ElementTree.write()?

There is an xml config file.

<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
  <Cache>
    <Index ID="DATE_INDEX">
      <FieldName Name="id"/>
      <FieldName Name="start_time"/>
      <FieldName Name="stop_time"/>
    </Index>
    <Index ID="USER_INDEX">
      <FieldName Name="id"/>
      <FieldName Name="username"/>
    </Index>
  </Cache>
  <Regions>
    <Region ID="0"   Folder="Unknown"/>
    <Region ID="100" Folder="MSK"/>
    <Region ID="200" Folder="SPB"/>
    <Region ID="300" Folder="PTZ"/>
  </Regions>
</Configuration>

to modify a file (Changes an existing entry) I use:
config_file = 'config.xml'
xml_config = ET.parse(config_file)
root = xml_config.getroot()
root[1][1].attrib['Folder'] = 'Capital'
xml_config.write('out.xml')

Everything works perfectly:
<Regions>
    <Region Folder="Unknown" ID="0" />
    <Region Folder="Capital" ID="100" />
    <Region Folder="SPB" ID="200" />
    <Region Folder="PTZ" ID="300" />
  </Regions>

To add an entry:
ET.SubElement(root[1], 'Region', {'Folder':"Ural", "ID":"400"})

but the output crashes editing:
It should be:
<Regions>
    <Region Folder="Unknown" ID="0" />
    <Region Folder="Capital" ID="100" />
    <Region Folder="SPB" ID="200" />
    <Region Folder="PTZ" ID="300" />
    <Region Folder="Ural" ID="400" />
  </Regions>

and I get this:
<Regions>
    <Region Folder="Unknown" ID="0" />
    <Region Folder="Capital" ID="100" />
    <Region Folder="SPB" ID="200" />
    <Region Folder="PTZ" ID="300" />
  <Region Folder="Ural" ID="400" /></Regions>

How can this be fixed?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis, 2015-08-18
@Norkotik

I made this workaround:

def Save_Xml_Pretty(elem, file):
    rough_string = ET.tostring(elem, 'utf-8')
    reparsed = minidom.parseString(rough_string)
    out = reparsed.toprettyxml(indent="\t")
    open(file, 'w').writelines(out)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question