Skip to main content
Participant
September 22, 2025
Answered

script csv to xml illustrator

  • September 22, 2025
  • 1 reply
  • 128 views
I'm trying to make a script for Illustrator to convert a CSV file to an XML file, but I always end up with the same error. I don't understand what I'm doing wrong. Could someone please take a look at the code? My head hurts from my own incompetence.
 

----------------------------------------------------------------

// CSVtoVariables_Valid.jsx
// Convierte un CSV en un XML válido para Illustrator y lo importa

function csvToXml(csvData) {
var lines = csvData.replace(/\r/g, "").split("\n");
var headers = lines[0].split(",");
var xmlOutput = '<?xml version="1.0" encoding="UTF-8"?>\n';
xmlOutput += '<variableLibrary xmlns="http://ns.adobe.com/Variables/1.0/">\n';
xmlOutput += ' <variables>\n';

for (var h = 0; h < headers.length; h++) {
var head = headers[h].replace(/^\s+|\s+$/g, "");
xmlOutput += ' <variable varName="' + head + '" trait="textcontent"/>\n';
}

xmlOutput += ' </variables>\n';
xmlOutput += ' <sampleDataSets>\n';

for (var i = 1; i < lines.length; i++) {
if (!lines[i] || lines[i].replace(/\s/g, "") === "") continue;
var data = lines[i].split(",");
xmlOutput += ' <sampleDataSet dataSetName="registro' + i + '">\n';
for (var j = 0; j < headers.length; j++) {
var head2 = headers[j].replace(/^\s+|\s+$/g, "");
var val = (data[j]) ? data[j].replace(/^\s+|\s+$/g, "") : "";
xmlOutput += ' <variableData varName="' + head2 + '"><p>' + val + '</p></variableData>\n';
}
xmlOutput += ' </sampleDataSet>\n';
}

xmlOutput += ' </sampleDataSets>\n';
xmlOutput += '</variableLibrary>';

return xmlOutput;
}

function main() {
if (!app.documents.length) {
alert("⚠️ Abre un documento antes de ejecutar el script.");
return;
}

var csvFile = File.openDialog("Selecciona un archivo CSV", "*.csv");
if (!csvFile) return;

csvFile.open("r");
var content = csvFile.read();
csvFile.close();

var xml = csvToXml(content);

var tmp = new File(Folder.desktop + "/CSV_IMPORT_VALID.xml");
tmp.encoding = "UTF-8";
tmp.open("w");
tmp.write(xml);
tmp.close();

try {
app.activeDocument.importVariables(tmp);
alert("✅ Variables importadas correctamente.\nArchivo generado: " + tmp.fsName);
} catch (e) {
alert("❌ Error importando: " + e);
}
}

main();

Correct answer creative explorer

@hans_4621 you might want to head over to GitHub, many open-source Illustrator scripts, including the Variable Importer, are hosted on GitHub, which is a great place to find, fork, and adapt existing code.

1 reply

creative explorer
Community Expert
creative explorerCommunity ExpertCorrect answer
Community Expert
September 26, 2025

@hans_4621 you might want to head over to GitHub, many open-source Illustrator scripts, including the Variable Importer, are hosted on GitHub, which is a great place to find, fork, and adapt existing code.

m