XhCode Online Converter Tools

CSV To XML Converter

Enter csv here:
1
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Results:
1
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
CSV To XML

To convert CSV (Comma-Separated Values) to XML format, each row in the CSV is typically represented as an individual XML element, with column headers used as tags for the data. This makes the data more structured and hierarchical, which is ideal for applications that require XML data.

Example:
CSV Input:

csv

name,age,city
Alice,30,New York
Bob,25,Los Angeles
Charlie,35,Chicago
Converted to XML Output:

xml

<people>
<person>
<name>Alice</name>
<age>30</age>
<city>New York</city>
</person>
<person>
<name>Bob</name>
<age>25</age>
<city>Los Angeles</city>
</person>
<person>
<name>Charlie</name>
<age>35</age>
<city>Chicago</city>
</person>
</people>
How to Convert CSV to XML:
Using Python:
You can use Python to convert CSV data into XML format using the csv module to read the CSV and xml.etree.ElementTree to construct XML.

Here's an example Python script that performs the conversion:

python

import csv
import xml.etree.ElementTree as ET

# Open the CSV file
with open('data.csv', mode='r') as file:
csv_reader = csv.DictReader(file)

# Create the root element for the XML
root = ET.Element("people")

# Process each row in the CSV and create XML elements
for row in csv_reader:
person = ET.SubElement(root, "person")
for key, value in row.items():
child = ET.SubElement(person, key)
child.text = value

# Create the tree and write to an XML file
tree = ET.ElementTree(root)
tree.write("data.xml", xml_declaration=True, encoding="utf-8")
How the Code Works:
It opens the CSV file and uses csv.DictReader to read it into a dictionary, where each row is a dictionary with column headers as keys.
It creates an XML structure with <people> as the root element.
For each row in the CSV, it creates a <person> element and adds sub-elements (<name>, <age>, <city>) for each field in the row.
The XML tree is written to an output file (data.xml).
Manual Conversion:
If you have a small dataset, you can manually convert CSV to XML by following these steps:

Define the root element (e.g., <people>).
For each row in the CSV, create an XML <person> element.
Add sub-elements within the <person> element for each field (using the CSV headers as element names).
For example:

CSV:

pgsql

name,age,city
Alice,30,New York
Bob,25,Los Angeles
Charlie,35,Chicago
Manually convert to:

xml

<people>
<person>
<name>Alice</name>
<age>30</age>
<city>New York</city>
</person>
<person>
<name>Bob</name>
<age>25</age>
<city>Los Angeles</city>
</person>
<person>
<name>Charlie</name>
<age>35</age>
<city>Chicago</city>
</person>
</people>
When to Convert CSV to XML:
When you need to provide data to systems or APIs that consume XML.
When you need to store or transmit hierarchical data.
When you need to integrate with applications that require XML (such as certain web services or database imports).

TOP