The following Python script reads a CSV file and converts it to XML, using the headers (first-line fields) as the XML element names.
Input file:
"Username","Identifier","First Name","Last Name" "booker12","9012","Rachel","Booker" "grey07","2070","Laura","Grey" "johnson81","4081","Craig","Johnson" "jenkins46","9346","Mary","Jenkins" "smith79","5079","Jamie","Smith"
Converter script:
#!/bin/python
# Converter: CSV to XML
import csv
import xml.etree.ElementTree as xml
input = 'input.csv'
output = 'output.xml'
# Open the CSV input file
file = open(input)
reader = csv.reader(file, delimiter=',', quotechar='"')
headers = next(reader)
# Map headers to their column indexes
indexes = {}
for header in headers:
indexes[header] = headers.index(header)
# Build the XML structure
root = xml.Element("Collection")
id = 0
for item in reader:
id = id + 1
# Create an entry element with an id attribute
entry = xml.Element("Entry")
entry.set('id', str(id))
root.append(entry)
# Add a child element for each field
for variable in indexes:
entry_property = xml.SubElement(entry, variable)
entry_property.text = item[indexes[variable]]
# Write the XML structure to a file
tree = xml.ElementTree(root)
with open(output, "wb") as output_file:
tree.write(output_file)
exit()
The script can be run by passing it to the Python interpreter:
python converter.py
Or by marking it as executable and running it directly:
chmod +x converter.py ./converter.py
The output file will look like this:
<Collection>
<Entry id="1">
<Username>booker12</Username>
<First Name>Rachel</First Name>
<Identifier>9012</Identifier>
<Last Name>Booker</Last Name>
</Entry>
<Entry id="2">
<Username>grey07</Username>
<First Name>Laura</First Name>
<Identifier>2070</Identifier>
<Last Name>Grey</Last Name>
</Entry>
<Entry id="3">
<Username>johnson81</Username>
<First Name>Craig</First Name>
<Identifier>4081</Identifier>
<Last Name>Johnson</Last Name>
</Entry>
<Entry id="4">
<Username>jenkins46</Username>
<First Name>Mary</First Name>
<Identifier>9346</Identifier>
<Last Name>Jenkins</Last Name>
</Entry>
<Entry id="5">
<Username>smith79</Username>
<First Name>Jamie</First Name>
<Identifier>5079</Identifier>
<Last Name>Smith</Last Name>
</Entry>
</Collection>