diff --git a/src/components/DevAreaTools/XmlFormatter.jsx b/src/components/DevAreaTools/XmlFormatter.jsx new file mode 100644 index 0000000..9597705 --- /dev/null +++ b/src/components/DevAreaTools/XmlFormatter.jsx @@ -0,0 +1,76 @@ +import React, { useState } from "react"; +// import { button } from "@/components/ui/button"; +// import { textarea } from "@/components/ui/textarea"; + +const XmlFormatter = () => { + const [input, setInput] = useState(""); + const [output, setOutput] = useState(""); + + const formatXml = (xml) => { + try { + const PADDING = " "; + const reg = /(>)(<)(\/*)/g; + let formatted = ""; + let pad = 0; + + xml = xml.replace(reg, "$1\r\n$2$3"); + xml.split("\r\n").forEach((node) => { + let indent = 0; + if (node.match(/.+<\/\w[^>]*>$/)) indent = 0; + else if (node.match(/^<\/\w/)) { + if (pad !== 0) pad -= 1; + } else if (node.match(/^<\w[^>]*[^\/]>.*$/)) indent = 1; + formatted += PADDING.repeat(pad) + node + "\r\n"; + pad += indent; + }); + return formatted.trim(); + } catch { + return "Invalid XML input."; + } + }; + + const handleFormat = () => { + try { + const parser = new DOMParser(); + const xmlDoc = parser.parseFromString(input, "application/xml"); + const parseError = xmlDoc.getElementsByTagName("parsererror"); + if (parseError.length) throw new Error("Invalid XML"); + setOutput(formatXml(input)); + } catch { + setOutput("❌ Invalid XML structure"); + } + }; + + const handleClear = () => { + setInput(""); + setOutput(""); + }; + + return ( +
+

XML Formatter

+