Pages

Wednesday, 27 November 2024

XML to JSON Converter Tool

XML to JSON Converter

XML to JSON Converter

Made with 💻 by YourName

/* General styles */ * { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: 'Arial', sans-serif; background-color: #f4f7fc; display: flex; justify-content: center; align-items: center; height: 100vh; padding: 20px; } .container { background-color: #ffffff; border-radius: 8px; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); width: 100%; max-width: 800px; padding: 20px; text-align: center; } h1 { font-size: 2rem; color: #333; margin-bottom: 20px; } .tool { display: flex; flex-direction: column; gap: 20px; } textarea { width: 100%; padding: 10px; font-size: 1rem; border: 1px solid #ccc; border-radius: 4px; min-height: 150px; resize: none; } textarea:focus { outline: none; border-color: #007bff; } button { padding: 10px 20px; font-size: 1rem; background-color: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; transition: background-color 0.3s; } button:hover { background-color: #0056b3; } footer { margin-top: 30px; font-size: 0.9rem; color: #888; } @media (max-width: 600px) { .tool { gap: 15px; } } function convertXMLToJSON() { let xmlInput = document.getElementById('xmlInput').value; let jsonOutputArea = document.getElementById('jsonOutput'); try { // Parse the XML string to XML object let parser = new DOMParser(); let xmlDoc = parser.parseFromString(xmlInput, "application/xml"); // Check for parsing errors if (xmlDoc.getElementsByTagName("parsererror").length) { throw new Error("Invalid XML format."); } // Convert the XML to a JSON object let jsonOutput = xmlToJson(xmlDoc); // Format the JSON output jsonOutputArea.value = JSON.stringify(jsonOutput, null, 2); } catch (error) { // Show error message if XML is invalid jsonOutputArea.value = `Error: ${error.message}`; } } function xmlToJson(xml) { let obj = {}; if (xml.nodeType === 1) { // Element node if (xml.attributes.length > 0) { obj["@attributes"] = {}; for (let i = 0; i < xml.attributes.length; i++) { let attribute = xml.attributes.item(i); obj["@attributes"][attribute.nodeName] = attribute.nodeValue; } } } else if (xml.nodeType === 3) { // Text node obj = xml.nodeValue; } // Process child nodes if (xml.hasChildNodes()) { for (let i = 0; i < xml.childNodes.length; i++) { let item = xml.childNodes.item(i); let nodeName = item.nodeName; if (typeof obj[nodeName] === "undefined") { obj[nodeName] = xmlToJson(item); } else { if (Array.isArray(obj[nodeName])) { obj[nodeName].push(xmlToJson(item)); } else { let temp = obj[nodeName]; obj[nodeName] = []; obj[nodeName].push(temp); obj[nodeName].push(xmlToJson(item)); } } } } return obj; }