Convert CSV to XML in Swift

Converting CSV files to the more versatile and user-friendly XML format for your web-based projects is a smart move, but not always the easiest one. To avoid complications that may arise with manual data formatting, we are going to discuss how to use an API to automatically convert CSV to XML. The only parameters that need to be met are your input file, API key, and a true/false indicator specifying if you want column names in the new XML document.

To call the conversion function in Swift, you simply need to input the above parameters in the following code:

import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
var semaphore = DispatchSemaphore (value: 0)let parameters = [
"key": "inputFile",
"src": "/path/to/file",
"type": "file"
]] as [[String : Any]]
let boundary = "Boundary-\(UUID().uuidString)"
var body = ""
var error: Error? = nil
for param in parameters {
if param["disabled"] == nil {
let paramName = param["key"]!
body += "--\(boundary)\r\n"
body += "Content-Disposition:form-data; name=\"\(paramName)\""
if param["contentType"] != nil {
body += "\r\nContent-Type: \(param["contentType"] as! String)"
let paramType = param["type"] as! String
if paramType == "text" {
let paramValue = param["value"] as! String
body += "\r\n\r\n\(paramValue)\r\n"
} else {
let paramSrc = param["src"] as! String
let fileData = try NSData(contentsOfFile:paramSrc, options:[]) as Data
let fileContent = String(data: fileData, encoding: .utf8)!
body += "; filename=\"\(paramSrc)\"\r\n"
+ "Content-Type: \"content-type header\"\r\n\r\n\(fileContent)\r\n"
body += "--\(boundary)--\r\n";
let postData = .utf8)
var request = URLRequest(url: URL(string: "")!,timeoutInterval: Double.infinity)
request.addValue("<boolean>", forHTTPHeaderField: "columnNamesFromFirstRow")
request.addValue("multipart/form-data", forHTTPHeaderField: "Content-Type")
request.addValue("YOUR-API-KEY-HERE", forHTTPHeaderField: "Apikey")
request.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
request.httpBody = postData
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data else {
print(String(describing: error))
print(String(data: data, encoding: .utf8)!)

Done! Your new XML file will be ready in seconds flat.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.