🔄 XML 转 JSON

将 XML 转换为 JSON,元素为对象、属性加 @ 前缀、文本内容为 #text。

等待转换...
已复制
const SAMPLE = 'XML 入门Alice30xmlweb'; function xmlToJson(node, withAttrs){ const obj = {}; if(withAttrs && node.attributes && node.attributes.length){ for(const attr of node.attributes) obj['@' + attr.name] = attr.value; } const kids = Array.from(node.children); if(kids.length === 0){ const txt = node.textContent.trim(); return txt || Object.keys(obj).length ? (Object.keys(obj).length ? (txt ? (obj['#text'] = txt, obj) : obj) : txt) : ''; } for(const k of kids){ const child = xmlToJson(k, withAttrs); if(obj[k.tagName] === undefined) obj[k.tagName] = child; else if(Array.isArray(obj[k.tagName])) obj[k.tagName].push(child); else obj[k.tagName] = [obj[k.tagName], child]; } return obj; } function doBeautify(){ convert(2); } function doMinify(){ convert(0); } function convert(indent){ setErr(''); try{ const doc = new DOMParser().parseFromString(document.getElementById('input').value, 'application/xml'); if(doc.getElementsByTagName('parsererror').length) throw new Error('XML 解析错误'); const withAttrs = document.getElementById('attrs').checked; const root = doc.documentElement; const result = {}; result[root.tagName] = xmlToJson(root, withAttrs); setOut(JSON.stringify(result, null, indent)); setErr('✅ 转换成功'); }catch(e){ setErr('❌ ' + e.message); } } function loadSample(){document.getElementById('input').value = SAMPLE; doBeautify();} function setOut(s){document.getElementById('output').textContent = s;} function setErr(s){const e = document.getElementById('err'); e.textContent = s || ''; e.className = 'err' + (s && s.startsWith('✅') ? ' ok' : '');} function clearAll(){document.getElementById('input').value = ''; setOut('等待转换...'); setErr('');} function getIndent(){const v=document.getElementById('indent').value;return v==='tab'?'\t':' '.repeat(parseInt(v));} function setOut(s){document.getElementById('output').textContent=s;} function setErr(s){const e=document.getElementById('err');e.textContent=s||'';e.className='err'+(s?'':' ok');} function clearAll(){document.getElementById('input').value='';setOut('等待输入...');setErr('');} function loadSample(){document.getElementById('input').value=SAMPLE;doBeautify();}