|
| 1 | +import React, { useState } from "react"; |
| 2 | +// import { button } from "@/components/ui/button"; |
| 3 | +// import { textarea } from "@/components/ui/textarea"; |
| 4 | + |
| 5 | +const XmlFormatter = () => { |
| 6 | + const [input, setInput] = useState(""); |
| 7 | + const [output, setOutput] = useState(""); |
| 8 | + |
| 9 | + const formatXml = (xml) => { |
| 10 | + try { |
| 11 | + const PADDING = " "; |
| 12 | + const reg = /(>)(<)(\/*)/g; |
| 13 | + let formatted = ""; |
| 14 | + let pad = 0; |
| 15 | + |
| 16 | + xml = xml.replace(reg, "$1\r\n$2$3"); |
| 17 | + xml.split("\r\n").forEach((node) => { |
| 18 | + let indent = 0; |
| 19 | + if (node.match(/.+<\/\w[^>]*>$/)) indent = 0; |
| 20 | + else if (node.match(/^<\/\w/)) { |
| 21 | + if (pad !== 0) pad -= 1; |
| 22 | + } else if (node.match(/^<\w[^>]*[^\/]>.*$/)) indent = 1; |
| 23 | + formatted += PADDING.repeat(pad) + node + "\r\n"; |
| 24 | + pad += indent; |
| 25 | + }); |
| 26 | + return formatted.trim(); |
| 27 | + } catch { |
| 28 | + return "Invalid XML input."; |
| 29 | + } |
| 30 | + }; |
| 31 | + |
| 32 | + const handleFormat = () => { |
| 33 | + try { |
| 34 | + const parser = new DOMParser(); |
| 35 | + const xmlDoc = parser.parseFromString(input, "application/xml"); |
| 36 | + const parseError = xmlDoc.getElementsByTagName("parsererror"); |
| 37 | + if (parseError.length) throw new Error("Invalid XML"); |
| 38 | + setOutput(formatXml(input)); |
| 39 | + } catch { |
| 40 | + setOutput("❌ Invalid XML structure"); |
| 41 | + } |
| 42 | + }; |
| 43 | + |
| 44 | + const handleClear = () => { |
| 45 | + setInput(""); |
| 46 | + setOutput(""); |
| 47 | + }; |
| 48 | + |
| 49 | + return ( |
| 50 | + <div className="flex flex-col gap-4 w-full max-w-2xl mx-auto"> |
| 51 | + <h2 className="text-xl font-semibold text-slate-800">XML Formatter</h2> |
| 52 | + <textarea |
| 53 | + placeholder="Paste your XML here..." |
| 54 | + value={input} |
| 55 | + onChange={(e) => setInput(e.target.value)} |
| 56 | + className="resize-none border border-slate-300" |
| 57 | + rows={6} |
| 58 | + /> |
| 59 | + |
| 60 | + <div className="flex gap-2"> |
| 61 | + <button onClick={handleFormat}>Format</button> |
| 62 | + <button onClick={handleClear} variant="outline">Clear</button> |
| 63 | + </div> |
| 64 | + |
| 65 | + <textarea |
| 66 | + placeholder="Formatted XML output..." |
| 67 | + value={output} |
| 68 | + readOnly |
| 69 | + className="resize-none border border-slate-300 font-mono text-sm" |
| 70 | + rows={8} |
| 71 | + /> |
| 72 | + </div> |
| 73 | + ); |
| 74 | +}; |
| 75 | + |
| 76 | +export default XmlFormatter; |
0 commit comments