Bonjour,
Depuis plusieurs jours, je suis confronté à un problème pour modifier des fichiers xml : impossible de maîtriser proprement l'indentation. J'ai essayé de multiples méthodes avec minidom ou etree mais à chaque fois, ou les nouvelles lignes n'ont aucune indentation ou l'indentation imposée vient s'ajouter à l'ancienne ce qui me donne vite des fichiers remplis d'espaces et retour à la lignes illisibles.
Mon fichier xml
Code XML : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 <?xml version="1.1" ?> <stations> <station id="ATE"> <evt class="local" lat="45" lon="3" prof="10" mag="4" date="2020-05-05T12:23:00"> <trace>toto.gif</trace> </evt> <evt class="tele" lat="45" lon="3" prof="10" mag="4" date="2020-05-05T12:23:00"> <trace>toto.gif</trace> </evt> </station> <station id="ABJF"> <evt class="local" lat="45" lon="3" prof="10" mag="4" date="2022-05-23T12:23:00"> <trace>tutu.gif</trace> </evt> <evt class="tele" lat="45" lon="3" prof="10" mag="4" date="2022-05-23T12:23:00"> <trace>tutu.gif</trace> </evt> </station> </stations>
Mon script python
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31 #! /usr/bin/python3 # -*- coding: UTF-8 -*- import xml.etree.ElementTree as ET liste_Stations = ['URDF', 'VALF'] stationsXML = './xml/stations_FR.old2' xml = ET.parse(stationsXML) stations = xml.getroot() for sta in liste_Stations: newSta = ET.SubElement(stations, 'station') newSta.attrib['id'] = sta newEvt = ET.SubElement(newSta, 'evt') newEvt.attrib['class'] = 'local' newTrace = ET.SubElement(newEvt, 'trace') temp = { 'class' : 'local', 'lat' : '0', 'lon' : '0', } newEvt.attrib = temp print(ET.tostring(stations))
Partager