')+'\n';if(line.match(/^<\w[^>]*[^\/]?>$/g)&&!line.match(/^<\w[^>]*\/>$/))indent++}
xmlInput.value=formatted.trim()});function setActiveTab(active){[tabPaste,tabUpload,tabUrl].forEach(tab=>{tab.classList.remove('bg-violet-600','text-white');tab.classList.add('bg-white','text-gray-700','border')});document.querySelectorAll('.panel').forEach(p=>p.classList.add('hidden'));if(active==='paste'){tabPaste.classList.add('bg-violet-600','text-white');tabPaste.classList.remove('bg-white','text-gray-700');panelPaste.classList.remove('hidden')}else if(active==='upload'){tabUpload.classList.add('bg-violet-600','text-white');tabUpload.classList.remove('bg-white','text-gray-700');panelUpload.classList.remove('hidden')}else if(active==='url'){tabUrl.classList.add('bg-violet-600','text-white');tabUrl.classList.remove('bg-white','text-gray-700');panelUrl.classList.remove('hidden')}}
tabPaste.addEventListener('click',()=>setActiveTab('paste'));tabUpload.addEventListener('click',()=>setActiveTab('upload'));tabUrl.addEventListener('click',()=>setActiveTab('url'));function updateUploadInfo(){const file=xmlFile.files[0];if(file){if(!file.name.toLowerCase().endsWith('.xml')&&!file.type.includes('xml')&&file.type!=='text/xml'&&file.type!=='application/xml'){showMessage('Please select an XML file.','error');xmlFile.value='';uploadFileInfo.classList.add('hidden');return}
uploadFileName.textContent=file.name.length>30?file.name.substring(0,27)+'...':file.name;uploadFileInfo.classList.remove('hidden');const reader=new FileReader();reader.onload=(e)=>{currentXmlContent=e.target.result;currentFileName=file.name.replace(/\.xml$/i,'')+'.json';showMessage(`Loaded XML file`,'success')};reader.readAsText(file)}else{uploadFileInfo.classList.add('hidden');currentXmlContent=null}}
xmlFile.addEventListener('change',updateUploadInfo);clearUpload.addEventListener('click',()=>{xmlFile.value='';uploadFileInfo.classList.add('hidden');currentXmlContent=null;showMessage('File cleared','info')});['dragenter','dragover','dragleave','drop'].forEach(ev=>{uploadDropZone.addEventListener(ev,(e)=>e.preventDefault())});['dragenter','dragover'].forEach(ev=>{uploadDropZone.addEventListener(ev,()=>{uploadDropZone.classList.add('border-violet-500','bg-violet-50')})});['dragleave','drop'].forEach(ev=>{uploadDropZone.addEventListener(ev,()=>{uploadDropZone.classList.remove('border-violet-500','bg-violet-50')})});uploadDropZone.addEventListener('drop',(e)=>{const dt=e.dataTransfer;const file=dt.files[0];if(file&&(file.name.toLowerCase().endsWith('.xml')||file.type.includes('xml'))){xmlFile.files=dt.files;updateUploadInfo()}else{showMessage('Please drop an XML file.','error')}});fetchUrlBtn.addEventListener('click',async()=>{const url=urlInput.value.trim();if(!url){showMessage('Please enter a URL','error');return}
fetchUrlBtn.disabled=!0;showMessage('Fetching...','info');try{const response=await fetch(url);if(!response.ok)throw new Error(`HTTP ${response.status}`);const xmlText=await response.text();currentXmlContent=xmlText;currentFileName='remote_data.json';showMessage(`Loaded XML from URL`,'success')}catch(err){showMessage('Fetch error: '+err.message,'error');currentXmlContent=null}finally{fetchUrlBtn.disabled=!1}});function xmlToJson(xmlString,ignoreAttrsFlag,alwaysArrayFlag){const parser=new DOMParser();const xmlDoc=parser.parseFromString(xmlString,'application/xml');const parseError=xmlDoc.getElementsByTagName('parsererror');if(parseError.length){throw new Error('Invalid XML: '+parseError[0].textContent)}
function convertElement(element){const obj={};const nodeName=element.nodeName;if(!ignoreAttrsFlag&&element.attributes&&element.attributes.length>0){obj['@attributes']={};for(let attr of element.attributes){obj['@attributes'][attr.nodeName]=attr.nodeValue}}
const childNodes=element.childNodes;const childCount=childNodes.length;if(childCount===1&&childNodes[0].nodeType===Node.TEXT_NODE){const text=childNodes[0].nodeValue.trim();if(text)obj['#text']=text}else{const elementChildren=[];for(let child of childNodes){if(child.nodeType===Node.ELEMENT_NODE){elementChildren.push(child)}}
if(elementChildren.length>0){for(let child of elementChildren){const childName=child.nodeName;const childObj=convertElement(child);if(alwaysArrayFlag){if(!obj[childName])obj[childName]=[];obj[childName].push(childObj)}else{if(obj.hasOwnProperty(childName)){if(!Array.isArray(obj[childName])){obj[childName]=[obj[childName]]}
obj[childName].push(childObj)}else{obj[childName]=childObj}}}}}
return obj}
const root=xmlDoc.documentElement;const rootObj=convertElement(root);return{[root.nodeName]:rootObj}}
convertBtn.addEventListener('click',()=>{let xmlText=null;let filename='data.json';if(currentXmlContent){xmlText=currentXmlContent;filename=currentFileName}else{xmlText=xmlInput.value.trim();if(!xmlText){showMessage('Please provide XML data (paste, file, or URL)','error');return}
filename='converted.json'}
const ignoreAttrsFlag=ignoreAttrs.checked;const alwaysArrayFlag=alwaysArray.checked;const spaces=indentSpaces.value==='0'?0:parseInt(indentSpaces.value);spinner.classList.remove('hidden');convertBtn.disabled=!0;showMessage('Converting...','info');setTimeout(()=>{try{const jsonObj=xmlToJson(xmlText,ignoreAttrsFlag,alwaysArrayFlag);const jsonOutput=JSON.stringify(jsonObj,null,spaces===0?undefined:spaces);updatePreview(jsonObj);const blob=new Blob([jsonOutput],{type:'application/json;charset=utf-8;'});const url=URL.createObjectURL(blob);const link=document.createElement('a');link.href=url;link.download=filename;document.body.appendChild(link);link.click();document.body.removeChild(link);URL.revokeObjectURL(url);showMessage(`✅ Converted XML to JSON`,'success')}catch(err){showMessage('Conversion error: '+err.message,'error');jsonPreview.textContent='Error: '+err.message}finally{spinner.classList.add('hidden');convertBtn.disabled=!1}},50)});setActiveTab('paste');xmlInput.value='\n \n John Doe\n XML Guide\n \n \n Jane Smith\n Advanced XML\n \n'})() Converting XML to JSON is a common task in modern web development, data processing, and API integration. Both XML (eXtensible Markup Language) and JSON (JavaScript Object Notation) are widely used formats for storing and exchanging data, but JSON has become more popular due to its simplicity and lightweight structure.
📌 What is XML?
- XML is a markup language used to store and transport data
- It uses tags to define elements and structure
- Commonly used in legacy systems and enterprise applications
- Example: configuration files, SOAP APIs
📌 What is JSON?
- JSON is a lightweight data-interchange format
- Easy to read and write for humans and machines
- Uses key-value pairs
- Widely used in REST APIs and modern web applications
There are several reasons why developers prefer converting XML into JSON:
- JSON is faster to parse in browsers and JavaScript environments
- Lightweight format reduces data transfer size
- Easier to integrate with modern APIs
- Better readability and simpler structure
- Supported natively in JavaScript
🧩 Basic Example of XML to JSON Conversion
XML Format:
<user>
<name>Rahul</name>
<age>30</age>
<city>Delhi</city>
</user>
Converted JSON:
{
"user": {
"name": "Rahul",
"age": 30,
"city": "Delhi"
}
}
⚙️ Methods to Convert XML to JSON
1. Using Online Tools
- Quick and easy method
- No coding required
- Paste XML and get JSON instantly
- Useful for beginners
2. Using JavaScript
- Ideal for web developers
- Can be done using DOMParser or libraries
Example:
const parser = new DOMParser();
const xml = `<user><name>Rahul</name></user>`;
const xmlDoc = parser.parseFromString(xml, "text/xml");const json = {
user: xmlDoc.getElementsByTagName("name")[0].textContent
};console.log(json);
3. Using Python
- Suitable for backend processing
Example:
import xmltodict
import jsonxml_data = "<user><name>Rahul</name></user>"
data_dict = xmltodict.parse(xml_data)
json_data = json.dumps(data_dict)print(json_data)
4. Using PHP
- Useful for WordPress or server-side apps
Example:
$xml = simplexml_load_string("<user><name>Rahul</name></user>");
$json = json_encode($xml);
echo $json;
🚧 Challenges in Conversion
- Handling attributes vs elements
- Nested XML structures can be complex
- Data type differences (string vs number)
- Repeated elements become arrays in JSON
💡 Best Practices
- Always validate XML before converting
- Use reliable libraries for large data
- Maintain consistent structure
- Test output JSON for accuracy
- Handle special characters carefully
🌐 Use Cases
- API data transformation
- WordPress plugin data handling
- Data migration between systems
- Mobile app backend integration
- SEO tools and analytics
✅ Conclusion
XML to JSON conversion is an essential process in today’s development ecosystem. While XML is still used in many systems, JSON’s simplicity and efficiency make it the preferred choice for modern applications. By using the right tools and methods, you can easily convert XML data into JSON format and improve performance, readability, and compatibility across platforms.