Come creare un file XML da Excel usando Python
Tempo di lettura stimato: 3 minuti
Stai lavorando a un progetto di analisi dei dati in cui hai bisogno di fornire i tuoi dati a una posizione che sia in grado di elaborare un file XML?
La capacità di ottenere i vostri dati in un formato strutturato come XML ha molti vantaggi:
(A) È possibile trasferire i dati a un servizio web per l'elaborazione.
(B) Più formati diversi dei vostri dati grezzi possono essere standardizzati, permettendo una rapida conversione ed elaborazione.
(C) I file XML possono essere letti da più programmi diversi, a patto di consegnarli nel formato corretto.
(D) Il destinatario dei dati può facilmente leggere il file XML e memorizzarlo nel suo database.
La capacità di usare questo metodo per leggere e trasferire i dati è un modo molto potente per aiutare un analista di dati ad elaborare grandi insiemi di dati.
Infatti, se state usando applicazioni basate sul cloud per analizzare le informazioni che state conservando, questo vi permetterà di consegnare rapidamente i dati.
Di quali pacchetti ho bisogno in Python?
Il primo passo è importare quanto segue:
import pandas as pd
from lxml import etree as et
Poi vogliamo leggere i dati di origine
In questo caso, stiamo leggendo un file excel
raw_data = pd.read_excel(r'Link to where your data is stored including the full file name')
Ora vogliamo iniziare a costruire la struttura XML
Il PRIMO PASSO è definire la radice
root = et.Element('root')
La radice è il genitore di tutti gli elementi di dati (tag) contenuti nel file XML ed è necessaria come parte della struttura
Il SECONDO PASSO è definire i nomi dei tag che memorizzeranno ogni riga dei dati sorgente
for row in raw_data.iterrows(): ==> This is a loop that takes runs through each record and populates for each tag.
root_tags = et.SubElement(root, 'ExportData') #=== > Root name
# These are the tag names for each row (SECTION 1)
Column_heading_1 = et.SubElement(root_tags, 'Name')
Column_heading_2 = et.SubElement(root_tags, 'Area')
Column_heading_3 = et.SubElement(root_tags, 'NoPurchases')
Column_heading_4 = et.SubElement(root_tags, 'Active')
###These are the values that will be populated for each row above
# The values inside the [] are the raw file column headings.(SECTION 2)
Column_heading_1.text = str(row[1]['Name'])
Column_heading_2.text = str(row[1]['Area'])
Column_heading_3.text = str(row[1]['No Purchases'])
Column_heading_4.text = str(row[1]['Active'])
Il file grezzo si presenta così:
Nome | Area | Nessun acquisto | Attivo |
John | Dublino | 2 | Y |
Maria | Galway | 3 | N |
Joe | Limerick | 4 | N |
Jimmy | Kilkenny | 55 | Y |
Jennifer | Belfast | 6 | N |
Susan | Waterford | 3 | Y |
Jake | Sughero | 1 | Y |
Bobby | Dundalk | 11 | N |
Sarah | Sligo | 9 | N |
Cian | Ennis | 8 | Y |
Il TERZO PASSO è creare il file XML e popolarlo con i dati del file di origine
# This Section outputs the data to an xml file
# Unless you tell it otherwise it saves it to the same folder as the script.
tree = et.ElementTree(root) ==> The variable tree is to hold all the values of "root"
et.indent(tree, space="\t", level=0) ===> This just formats in a way that the XML is readable
tree.write('output.xml', encoding="utf-8") ==> The data is saved to an XML file
L'output XML dovrebbe assomigliare al seguente
<root>
<ExportData>
<Name>John</Name>
<Area>Dublin</Area>
<NoPurchases>2</NoPurchases>
<Active>Y</Active>
</ExportData>
<ExportData>
<Name>Mary</Name>
<Area>Galway</Area>
<NoPurchases>3</NoPurchases>
<Active>N</Active>
</ExportData>
<ExportData>
<Name>Joe</Name>
<Area>Limerick</Area>
<NoPurchases>4</NoPurchases>
<Active>N</Active>
</ExportData>
<ExportData>
<Name>Jimmy</Name>
<Area>Kilkenny</Area>
<NoPurchases>55</NoPurchases>
<Active>Y</Active>
</ExportData>
<ExportData>
<Name>Jennifer</Name>
<Area>Belfast</Area>
<NoPurchases>6</NoPurchases>
<Active>N</Active>
</ExportData>
<ExportData>
<Name>Susan</Name>
<Area>Waterford</Area>
<NoPurchases>3</NoPurchases>
<Active>Y</Active>
</ExportData>
<ExportData>
<Name>Jake</Name>
<Area>Cork</Area>
<NoPurchases>1</NoPurchases>
<Active>Y</Active>
</ExportData>
<ExportData>
<Name>Bobby</Name>
<Area>Dundalk</Area>
<NoPurchases>11</NoPurchases>
<Active>N</Active>
</ExportData>
<ExportData>
<Name>Sarah</Name>
<Area>Sligo</Area>
<NoPurchases>9</NoPurchases>
<Active>N</Active>
</ExportData>
<ExportData>
<Name>Cian</Name>
<Area>Ennis</Area>
<NoPurchases>8</NoPurchases>
<Active>Y</Active>
</ExportData>
</root>
Si possono aggiungere altri dati XML
- Aggiungere altre righe - Tutto quello che dovete fare è aggiungere al file sorgente e salvare. Quando rilancerete la logica, essa leggerà le informazioni extra.
- Aggiungere altre colonne - Tutto quello che devi fare è andare al secondo passo sopra, aggiungere un nome di tag alla SEZIONE 1. Separatamente dovrai aggiungere un'ulteriore colonna con dati al file di origine, e poi aggiungere quel nome di colonna anche alla SEZIONE 2