fix: misc

This commit is contained in:
Ibrahima G. Coulibaly
2025-03-18 19:20:54 +00:00
parent f4f09f4852
commit 6bcf9ebf8a
5 changed files with 69 additions and 79 deletions

View File

@@ -56,13 +56,7 @@ export default function CsvToXml({ title }: ToolComponentProps) {
const compute = (values: InitialValuesType, input: string) => {
if (input) {
try {
const xmlResult = convertCsvToXml(input, {
delimiter: values.delimiter,
quote: values.quote,
comment: values.comment,
useHeaders: values.useHeaders,
skipEmptyLines: values.skipEmptyLines
});
const xmlResult = convertCsvToXml(input, values);
setResult(xmlResult);
} catch (error) {
setResult(

View File

@@ -4,7 +4,7 @@ import { lazy } from 'react';
export const tool = defineTool('csv', {
name: 'Convert CSV to XML',
path: 'csv-to-xml',
icon: 'lets-icons:xml-light',
icon: 'mdi-light:xml',
description: 'Convert CSV files to XML format with customizable options.',
shortDescription: 'Convert CSV data to XML format',
keywords: ['csv', 'xml', 'convert', 'transform', 'parse'],

View File

@@ -6,19 +6,10 @@ type CsvToXmlOptions = {
skipEmptyLines: boolean;
};
const defaultOptions: CsvToXmlOptions = {
delimiter: ',',
quote: '"',
comment: '#',
useHeaders: true,
skipEmptyLines: true
};
export const convertCsvToXml = (
csv: string,
options: Partial<CsvToXmlOptions> = {}
options: CsvToXmlOptions
): string => {
const opts = { ...defaultOptions, ...options };
const lines = csv.split('\n').map((line) => line.trim());
let xmlResult = `<?xml version="1.0" encoding="UTF-8" ?>\n<root>\n`;
@@ -27,21 +18,21 @@ export const convertCsvToXml = (
const validLines = lines.filter(
(line) =>
line &&
!line.startsWith(opts.comment) &&
(!opts.skipEmptyLines || line.trim() !== '')
!line.startsWith(options.comment) &&
(!options.skipEmptyLines || line.trim() !== '')
);
if (validLines.length === 0) {
return `<?xml version="1.0" encoding="UTF-8" ?>\n<root></root>`;
}
if (opts.useHeaders) {
headers = parseCsvLine(validLines[0], opts);
if (options.useHeaders) {
headers = parseCsvLine(validLines[0], options);
validLines.shift();
}
validLines.forEach((line, index) => {
const values = parseCsvLine(line, opts);
const values = parseCsvLine(line, options);
xmlResult += ` <row id="${index}">\n`;
headers.forEach((header, i) => {
xmlResult += ` <${header}>${values[i] || ''}</${header}>\n`;