轉換規則
- 元素節點 → 物件:屬性存入
@attributes,子元素以標籤名為鍵。
- 文字節點 → 字串值。
- 同名同層子元素 → 陣列。
- 混合內容(文字+元素) → 文字存入
#text。
通用遞歸函式
function xmlToJson(xmlNode) {
// 文字/CDATA 節點
if (xmlNode.nodeType === Node.TEXT_NODE || xmlNode.nodeType === Node.CDATA_SECTION_NODE) {
const text = xmlNode.nodeValue.trim();
return text || undefined; // 忽略純空白
}
// 註釋節點忽略
if (xmlNode.nodeType === Node.COMMENT_NODE) return undefined;
// 元素節點
if (xmlNode.nodeType === Node.ELEMENT_NODE) {
const obj = {};
// 處理屬性
if (xmlNode.attributes && xmlNode.attributes.length > 0) {
obj['@attributes'] = {};
for (const attr of xmlNode.attributes) {
obj['@attributes'][attr.name] = attr.value;
}
}
// 處理子節點
const children = [...xmlNode.childNodes].map(xmlToJson).filter(v => v !== undefined);
if (children.length === 0) return Object.keys(obj).length ? obj : ''; // 空元素
// 合併同名子元素
children.forEach(child => {
const key = Object.keys(child)[0];
const value = child[key];
if (key in obj) {
if (!Array.isArray(obj[key])) obj[key] = [obj[key]];
obj[key].push(value);
} else {
obj[key] = value;
}
});
return { [xmlNode.nodeName]: obj };
}
return undefined;
}
// 使用範例
const xmlStr = `
`;
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlStr, 'application/xml');
const json = xmlToJson(xmlDoc.documentElement);
console.log(JSON.stringify(json, null, 2));
輸出 JSON 結構
{
"ALEXA": {
"@attributes": { "VER": "0.9", "URL": "davidwalsh.name/", "HOME": "0", "AID": "=" },
"SD": [
{
"@attributes": { "TITLE": "A", "FLAGS": "", "HOST": "davidwalsh.name" },
"TITLE": { "@attributes": { "TEXT": "David Walsh Blog" } },
"LINKSIN": { "@attributes": { "NUM": "1102" } },
"SPEED": { "@attributes": { "TEXT": "1421", "PCT": "51" } }
},
{
"POPULARITY": { "@attributes": { "URL": "davidwalsh.name/", "TEXT": "7131" } },
"REACH": { "@attributes": { "RANK": "5952" } },
"RANK": { "@attributes": { "DELTA": "-1648" } }
}
]
}
}
進階擴展
- 命名空間支援:
nodeName 含前綴,可拆分 ns:localName。
- 混合內容處理:文字節點與元素節點並存時,將文字存入
#text 鍵。
- 型別推斷:數值字串轉
Number、"true"/"false" 轉 Boolean。
- 串流處理大 XML:使用
SAXParser (如 sax-js) 邊解析邊轉換,避免記憶體爆炸。
現有庫推薦
xml2js(Node.js 經典、支援 Promise、可配置)。
fast-xml-parser(高效能、無依賴、支援瀏覽器)。
xmldom + 自定義遍歷(瀏覽器端無 DOMParser 時的 polyfill)。