🔧 JSON 转 XML

将 JSON 转换为 XML,支持对象、数组、嵌套结构,可自定义根节点名。

等待转换...
已复制
const SAMPLE = JSON.stringify({user:{name:"Alice",age:30,roles:["admin","user"],address:{city:"SH",zip:"200000"},active:true}}, null, 2); function escapeXml(s){ return String(s).replace(/&/g,'&').replace(//g,'>').replace(/"/g,'"').replace(/'/g,'''); } function validTag(k){ return /^[A-Za-z_][\w.-]*$/.test(k) ? k : '_' + k.replace(/[^\w.-]/g, '_'); } function toXml(v, tag, indent, depth){ const pad = ' '.repeat(depth); const t = validTag(tag); if(v === null) return pad + '<' + t + ' null="true" />'; if(typeof v === 'boolean' || typeof v === 'number') return pad + '<' + t + '>' + v + ''; if(typeof v === 'string') return pad + '<' + t + '>' + escapeXml(v) + ''; if(Array.isArray(v)){ if(indent) return v.map(item => toXml(item, tag, indent, depth)).join('\n'); return v.map(item => toXml(item, tag, indent, depth)).join(''); } if(typeof v === 'object'){ const inner = Object.entries(v).map(([k, val]) => toXml(val, k, indent, depth + 1)).join(indent ? '\n' : ''); if(indent) return pad + '<' + t + '>\n' + inner + '\n' + pad + ''; return '<' + t + '>' + inner + ''; } return pad + '<' + t + '>' + escapeXml(String(v)) + ''; } function doBeautify(){ convert(true); } function doMinify(){ convert(false); } function convert(indent){ setErr(''); try{ const data = JSON.parse(document.getElementById('input').value); const root = document.getElementById('root').value || 'root'; const decl = '\n'; setOut(decl + toXml(data, root, indent, 0)); 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();}