-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathxml-formatter.html
More file actions
394 lines (331 loc) · 14.7 KB
/
xml-formatter.html
File metadata and controls
394 lines (331 loc) · 14.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>XML Formatter</title>
<link rel="stylesheet" href="common.css">
<style>
body { display: flex; flex-direction: column; }
.options { display: flex; gap: 16px; align-items: center; flex-wrap: wrap; }
</style>
</head>
<body>
<a href="index.html" class="back-link">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M19 12H5M12 19l-7-7 7-7"/>
</svg>
All Tools
</a>
<header>
<h1>XML Formatter</h1>
<p class="subtitle">Pretty print or minify XML</p>
</header>
<div class="controls">
<button id="formatBtn">Format</button>
<button id="minifyBtn">Minify</button>
<button id="clearBtn" class="secondary">Clear</button>
<div class="options">
<div class="option-group">
<label for="indentSelect">Indent:</label>
<select id="indentSelect">
<option value="2">2 spaces</option>
<option value="4">4 spaces</option>
<option value="tab">Tab</option>
</select>
</div>
<div class="option-group">
<input type="checkbox" id="preserveComments" checked>
<label for="preserveComments">Preserve comments</label>
</div>
</div>
</div>
<div class="container">
<div class="pane">
<div class="pane-header">
<span class="label">
<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
<polyline points="14 2 14 8 20 8"></polyline>
</svg>
Input
<span id="statusIndicator" class="status-indicator"></span>
</span>
</div>
<textarea id="inputArea" placeholder='Paste your XML here...
Example:
<?xml version="1.0"?><root><item id="1"><name>Test</name></item></root>' spellcheck="false"></textarea>
<div id="errorMessage" class="error-message"></div>
</div>
<div class="pane">
<div class="pane-header">
<span class="label">
<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
<polyline points="14 2 14 8 20 8"></polyline>
<line x1="16" y1="13" x2="8" y2="13"></line>
<line x1="16" y1="17" x2="8" y2="17"></line>
</svg>
Output
</span>
<button id="copyBtn" class="copy-btn">Copy</button>
</div>
<textarea id="outputArea" readonly placeholder="Formatted XML will appear here..." spellcheck="false"></textarea>
</div>
</div>
<script>
const inputArea = document.getElementById('inputArea');
const outputArea = document.getElementById('outputArea');
const formatBtn = document.getElementById('formatBtn');
const minifyBtn = document.getElementById('minifyBtn');
const clearBtn = document.getElementById('clearBtn');
const copyBtn = document.getElementById('copyBtn');
const indentSelect = document.getElementById('indentSelect');
const preserveCommentsCheckbox = document.getElementById('preserveComments');
const errorMessage = document.getElementById('errorMessage');
const statusIndicator = document.getElementById('statusIndicator');
// Elements that should preserve whitespace
const preserveWhitespaceElements = new Set(['pre', 'code']);
function getIndent(indentValue) {
return indentValue === 'tab' ? '\t' : ' '.repeat(parseInt(indentValue, 10));
}
function escapeXml(str) {
return str
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function formatNode(node, indent, level, preserveWS, preserveComments) {
const indentStr = indent.repeat(level);
if (node.nodeType === Node.TEXT_NODE) {
const text = node.textContent;
if (preserveWS) {
return text;
}
const trimmed = text.trim();
if (!trimmed) return '';
return trimmed;
}
if (node.nodeType === Node.COMMENT_NODE) {
if (!preserveComments) return '';
return `${indentStr}<!--${node.textContent}-->`;
}
if (node.nodeType === Node.CDATA_SECTION_NODE) {
return `${indentStr}<![CDATA[${node.textContent}]]>`;
}
if (node.nodeType === Node.PROCESSING_INSTRUCTION_NODE) {
return `${indentStr}<?${node.target} ${node.data}?>`;
}
if (node.nodeType !== Node.ELEMENT_NODE) {
return '';
}
const tagName = node.tagName;
const shouldPreserveWS = preserveWhitespaceElements.has(tagName.toLowerCase());
// Build opening tag
let openTag = `<${tagName}`;
// Handle namespaces and attributes
for (const attr of node.attributes) {
const attrValue = attr.value.replace(/"/g, '"');
openTag += ` ${attr.name}="${attrValue}"`;
}
// Get children
const children = Array.from(node.childNodes);
// Self-closing tag for empty elements
if (children.length === 0) {
return `${indentStr}${openTag}/>`;
}
openTag += '>';
// Handle content
if (shouldPreserveWS) {
// Preserve whitespace for pre, code, etc.
let content = '';
for (const child of children) {
if (child.nodeType === Node.TEXT_NODE) {
content += child.textContent;
} else if (child.nodeType === Node.CDATA_SECTION_NODE) {
content += `<![CDATA[${child.textContent}]]>`;
} else if (child.nodeType === Node.ELEMENT_NODE) {
content += formatNode(child, indent, 0, true, preserveComments);
}
}
return `${indentStr}${openTag}${content}</${tagName}>`;
}
// Check if content is simple (single text node)
const hasOnlyText = children.length === 1 && children[0].nodeType === Node.TEXT_NODE;
if (hasOnlyText) {
const text = children[0].textContent.trim();
return `${indentStr}${openTag}${text}</${tagName}>`;
}
// Check for mixed content (text + elements)
const hasTextContent = children.some(child =>
child.nodeType === Node.TEXT_NODE && child.textContent.trim()
);
const hasElementContent = children.some(child =>
child.nodeType === Node.ELEMENT_NODE
);
if (hasTextContent && hasElementContent) {
// Mixed content - keep on same line to preserve semantics
let content = '';
for (const child of children) {
if (child.nodeType === Node.TEXT_NODE) {
content += child.textContent.trim();
} else {
content += formatNode(child, '', 0, false, preserveComments);
}
}
return `${indentStr}${openTag}${content}</${tagName}>`;
}
// Multi-line formatting for element-only content
let result = `${indentStr}${openTag}\n`;
for (const child of children) {
const childResult = formatNode(child, indent, level + 1, false, preserveComments);
if (childResult) {
result += childResult + '\n';
}
}
result += `${indentStr}</${tagName}>`;
return result;
}
function formatXML(xml, indent, preserveComments) {
const parser = new DOMParser();
const doc = parser.parseFromString(xml, 'text/xml');
// Check for parsing errors
const errorNode = doc.querySelector('parsererror');
if (errorNode) {
// Extract error message
const errorText = errorNode.textContent;
throw new Error(errorText.split('\n')[0] || 'Invalid XML');
}
let result = '';
// Handle XML declaration if present in original
const xmlDeclMatch = xml.match(/^<\?xml[^?]*\?>/);
if (xmlDeclMatch) {
result += xmlDeclMatch[0] + '\n';
}
// Format the document content
for (const child of doc.childNodes) {
if (child.nodeType === Node.PROCESSING_INSTRUCTION_NODE) {
result += `<?${child.target} ${child.data}?>\n`;
} else if (child.nodeType === Node.COMMENT_NODE && preserveComments) {
result += `<!--${child.textContent}-->\n`;
} else if (child.nodeType === Node.ELEMENT_NODE) {
result += formatNode(child, indent, 0, false, preserveComments);
}
}
return result.trim();
}
function minifyXML(xml, preserveComments) {
const parser = new DOMParser();
const doc = parser.parseFromString(xml, 'text/xml');
// Check for parsing errors
const errorNode = doc.querySelector('parsererror');
if (errorNode) {
const errorText = errorNode.textContent;
throw new Error(errorText.split('\n')[0] || 'Invalid XML');
}
function minifyNode(node) {
if (node.nodeType === Node.TEXT_NODE) {
const tagName = node.parentElement?.tagName?.toLowerCase();
if (preserveWhitespaceElements.has(tagName)) {
return node.textContent;
}
return node.textContent.replace(/\s+/g, ' ').trim();
}
if (node.nodeType === Node.COMMENT_NODE) {
return preserveComments ? `<!--${node.textContent}-->` : '';
}
if (node.nodeType === Node.CDATA_SECTION_NODE) {
return `<![CDATA[${node.textContent}]]>`;
}
if (node.nodeType === Node.PROCESSING_INSTRUCTION_NODE) {
return `<?${node.target} ${node.data}?>`;
}
if (node.nodeType !== Node.ELEMENT_NODE) {
return '';
}
const tagName = node.tagName;
let openTag = `<${tagName}`;
for (const attr of node.attributes) {
const attrValue = attr.value.replace(/"/g, '"');
openTag += ` ${attr.name}="${attrValue}"`;
}
const children = Array.from(node.childNodes);
if (children.length === 0) {
return `${openTag}/>`;
}
openTag += '>';
let content = '';
for (const child of children) {
const minified = minifyNode(child);
if (minified) {
content += minified;
}
}
return `${openTag}${content}</${tagName}>`;
}
let result = '';
// Handle XML declaration if present in original
const xmlDeclMatch = xml.match(/^<\?xml[^?]*\?>/);
if (xmlDeclMatch) {
result += xmlDeclMatch[0];
}
for (const child of doc.childNodes) {
result += minifyNode(child);
}
return result;
}
function format(minify = false) {
const input = inputArea.value.trim();
errorMessage.style.display = 'none';
statusIndicator.className = 'status-indicator';
if (!input) {
outputArea.value = '';
return;
}
try {
const preserveComments = preserveCommentsCheckbox.checked;
if (minify) {
outputArea.value = minifyXML(input, preserveComments);
} else {
const indent = getIndent(indentSelect.value);
outputArea.value = formatXML(input, indent, preserveComments);
}
statusIndicator.className = 'status-indicator valid';
} catch (e) {
errorMessage.style.display = 'block';
errorMessage.textContent = e.message;
outputArea.value = '';
statusIndicator.className = 'status-indicator invalid';
}
}
formatBtn.addEventListener('click', () => format(false));
minifyBtn.addEventListener('click', () => format(true));
// Auto-format on input
inputArea.addEventListener('input', () => format(false));
clearBtn.addEventListener('click', () => {
inputArea.value = '';
outputArea.value = '';
errorMessage.style.display = 'none';
statusIndicator.className = 'status-indicator';
inputArea.focus();
});
copyBtn.addEventListener('click', () => {
if (!outputArea.value) return;
navigator.clipboard.writeText(outputArea.value).then(() => {
const originalText = copyBtn.textContent;
copyBtn.textContent = 'Copied!';
copyBtn.classList.add('copied');
setTimeout(() => {
copyBtn.textContent = originalText;
copyBtn.classList.remove('copied');
}, 2000);
});
});
// Re-format when options change
indentSelect.addEventListener('change', () => format(false));
preserveCommentsCheckbox.addEventListener('change', () => format(false));
</script>
</body>
</html>