diff --git a/src/pages/tools/csv/csv-to-xml/csv-to-xml.service.test.ts b/src/pages/tools/csv/csv-to-xml/csv-to-xml.service.test.ts
index ca9cf5a1..cea67ca5 100644
--- a/src/pages/tools/csv/csv-to-xml/csv-to-xml.service.test.ts
+++ b/src/pages/tools/csv/csv-to-xml/csv-to-xml.service.test.ts
@@ -11,7 +11,10 @@ const defaultOptions = {
describe('convertCsvToXml', () => {
it('should convert basic CSV to XML with headers', () => {
- const result = convertCsvToXml('name,age\nJohn,30\nAlice,25', defaultOptions);
+ const result = convertCsvToXml(
+ 'name,age\nJohn,30\nAlice,25',
+ defaultOptions
+ );
expect(result).toContain('John');
expect(result).toContain('Alice');
expect(result).toContain('30');
@@ -35,14 +38,20 @@ describe('convertCsvToXml', () => {
});
it('should handle normal data without corruption', () => {
- const result = convertCsvToXml('name,age,city\nJohn,30,New York', defaultOptions);
+ const result = convertCsvToXml(
+ 'name,age,city\nJohn,30,New York',
+ defaultOptions
+ );
expect(result).toContain('John');
expect(result).toContain('30');
expect(result).toContain('New York');
});
it('should sanitize header names containing spaces', () => {
- const result = convertCsvToXml('first name,last name\nJohn,Doe', defaultOptions);
+ const result = convertCsvToXml(
+ 'first name,last name\nJohn,Doe',
+ defaultOptions
+ );
expect(result).toContain('John');
expect(result).toContain('Doe');
});
@@ -56,7 +65,9 @@ describe('convertCsvToXml', () => {
it('should return empty root element for empty input', () => {
const result = convertCsvToXml('', defaultOptions);
- expect(result).toBe('\n');
+ expect(result).toBe(
+ '\n'
+ );
});
it('should include XML declaration', () => {
@@ -70,6 +81,6 @@ describe('convertCsvToXml', () => {
expect(result).toContain('<');
expect(result).toContain('>');
expect(result).toContain('"');
- expect(result).toContain(''');
+ expect(result).toContain(''');
});
});
diff --git a/src/pages/tools/csv/csv-to-xml/index.tsx b/src/pages/tools/csv/csv-to-xml/index.tsx
index 1178a81f..892e0420 100644
--- a/src/pages/tools/csv/csv-to-xml/index.tsx
+++ b/src/pages/tools/csv/csv-to-xml/index.tsx
@@ -8,14 +8,7 @@ import { ToolComponentProps } from '@tools/defineTool';
import { Box } from '@mui/material';
import CheckboxWithDesc from '@components/options/CheckboxWithDesc';
import TextFieldWithDesc from '@components/options/TextFieldWithDesc';
-
-type InitialValuesType = {
- delimiter: string;
- quote: string;
- comment: string;
- useHeaders: boolean;
- skipEmptyLines: boolean;
-};
+import { InitialValuesType } from './types';
const initialValues: InitialValuesType = {
delimiter: ',',
diff --git a/src/pages/tools/csv/csv-to-xml/service.ts b/src/pages/tools/csv/csv-to-xml/service.ts
index a72ba34f..3f9f6b8f 100644
--- a/src/pages/tools/csv/csv-to-xml/service.ts
+++ b/src/pages/tools/csv/csv-to-xml/service.ts
@@ -1,38 +1,10 @@
-type CsvToXmlOptions = {
- delimiter: string;
- quote: string;
- comment: string;
- useHeaders: boolean;
- skipEmptyLines: boolean;
-};
-
-/**
- * Escape special XML characters in text content.
- */
-const escapeXml = (text: string): string => {
- return text
- .replace(/&/g, '&')
- .replace(//g, '>')
- .replace(/"/g, '"')
- .replace(/'/g, ''');
-};
-
-/**
- * Sanitize a string so it can be used as a valid XML element name.
- * Replaces characters that are not allowed in XML names with underscores.
- */
-const sanitizeXmlElementName = (name: string): string => {
- // XML element names must start with a letter or underscore,
- // and may only contain letters, digits, hyphens, underscores, and periods.
- return name
- .replace(/^[^a-zA-Z_]+/, '')
- .replace(/[^a-zA-Z0-9_\-.]/g, '_');
-};
+import { InitialValuesType } from './types';
+import { escapeMarkup } from '@utils/string';
+import { normalizeXmlTagName } from '@utils/xml';
export const convertCsvToXml = (
csv: string,
- options: CsvToXmlOptions
+ options: InitialValuesType
): string => {
const lines = csv.split('\n').map((line) => line.trim());
@@ -51,15 +23,23 @@ export const convertCsvToXml = (
}
if (options.useHeaders) {
- headers = parseCsvLine(validLines[0], options).map(sanitizeXmlElementName);
+ headers = parseCsvLine(validLines[0], options).map(normalizeXmlTagName);
validLines.shift();
+ } else {
+ // No header row to source tag names from - fall back to positional
+ // column names (col1, col2, ...) based on the first data row's width,
+ // so rows still get real field tags instead of coming out empty.
+ const columnCount = parseCsvLine(validLines[0], options).length;
+ headers = Array.from({ length: columnCount }, (_, i) => `col${i + 1}`);
}
validLines.forEach((line, index) => {
const values = parseCsvLine(line, options);
xmlResult += ` \n`;
headers.forEach((header, i) => {
- xmlResult += ` <${header}>${escapeXml(values[i] || '')}${header}>\n`;
+ xmlResult += ` <${header}>${escapeMarkup(
+ values[i] || ''
+ )}${header}>\n`;
});
xmlResult += `
\n`;
});
@@ -68,7 +48,7 @@ export const convertCsvToXml = (
return xmlResult;
};
-const parseCsvLine = (line: string, options: CsvToXmlOptions): string[] => {
+const parseCsvLine = (line: string, options: InitialValuesType): string[] => {
const values: string[] = [];
let currentValue = '';
let inQuotes = false;
@@ -76,9 +56,25 @@ const parseCsvLine = (line: string, options: CsvToXmlOptions): string[] => {
for (let i = 0; i < line.length; i++) {
const char = line[i];
- if (char === options.quote) {
- inQuotes = !inQuotes;
- } else if (char === options.delimiter && !inQuotes) {
+ if (inQuotes) {
+ if (char === options.quote) {
+ // A doubled quote ("") inside a quoted field is an escaped
+ // literal quote, not the end of the field.
+ if (line[i + 1] === options.quote) {
+ currentValue += options.quote;
+ i++;
+ } else {
+ inQuotes = false;
+ }
+ } else {
+ currentValue += char;
+ }
+ } else if (char === options.quote && currentValue === '') {
+ // Only treat a quote as opening a quoted field when it's the very
+ // first character of the field - a quote appearing mid-field
+ // (e.g. `say "hello"`) is just literal text, not a CSV delimiter.
+ inQuotes = true;
+ } else if (char === options.delimiter) {
values.push(currentValue.trim());
currentValue = '';
} else {
diff --git a/src/pages/tools/csv/csv-to-xml/types.ts b/src/pages/tools/csv/csv-to-xml/types.ts
new file mode 100644
index 00000000..f45e44e8
--- /dev/null
+++ b/src/pages/tools/csv/csv-to-xml/types.ts
@@ -0,0 +1,7 @@
+export type InitialValuesType = {
+ delimiter: string;
+ quote: string;
+ comment: string;
+ useHeaders: boolean;
+ skipEmptyLines: boolean;
+};