萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 將 XML 轉換為 JSON 的通用遞歸算法

轉換規則

  • 元素節點 → 物件:屬性存入 @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 = `

  
    
    <LINKSIN NUM="1102" />
    <SPEED TEXT="1421" PCT="51" />
  </SD>
  <SD>
    <POPULARITY URL="davidwalsh.name/" TEXT="7131" />
    <REACH RANK="5952" />
    <RANK DELTA="-1648" />
  </SD>
</ALEXA>
`;

const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlStr, 'application/xml');
const json = xmlToJson(xmlDoc.documentElement);
console.log(JSON.stringify(json, null, 2));
</code></pre>

<h2>輸出 JSON 結構</h2>
<pre><code>{
  "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" } }
      }
    ]
  }
}
</code></pre>

<h2>進階擴展</h2>
<ul>
<li><strong>命名空間支援</strong>:<code>nodeName</code> 含前綴,可拆分 <code>ns:localName</code>。</li>
<li><strong>混合內容處理</strong>:文字節點與元素節點並存時,將文字存入 <code>#text</code> 鍵。</li>
<li><strong>型別推斷</strong>:數值字串轉 <code>Number</code>、<code>"true"/"false"</code> 轉 <code>Boolean</code>。</li>
<li><strong>串流處理大 XML</strong>:使用 <code>SAXParser</code> (如 <code>sax-js</code>) 邊解析邊轉換,避免記憶體爆炸。</li>
</ul>

<h2>現有庫推薦</h2>
<ul>
<li><code>xml2js</code>(Node.js 經典、支援 Promise、可配置)。</li>
<li><code>fast-xml-parser</code>(高效能、無依賴、支援瀏覽器)。</li>
<li><code>xmldom</code> + 自定義遍歷(瀏覽器端無 DOMParser 時的 polyfill)。</li>
</ul>
						<div class="ad2">
							<script language='javascript' src='/ad/tad.js'></script>
						</div>
					</div>
					<div>
						<div class="pageNum">
							<ul>
								<li>上一篇程序編程: <a class='LinkPrevArticle' href='https://twcomputer.wsxdn.com/programming/scripttopics/javascript/201510/69490.html' >JavaScript delete 運算符深度解析:刪除屬性、陣列漏洞與變數刪除怪象</a> <li>下一篇程序編程: <a class='LinkNextArticle' href='https://twcomputer.wsxdn.com/programming/scripttopics/javascript/201510/69492.html'  >JavaScript 倒計時類實現:毫秒級精度、回調支援、自動銷毀</a> 
							</ul>
						</div>
					</div>
					<div class=kenbxne_js></div>
				</div>
				<div class=kenbxne_js></div>
			</div>
			<div class=kenbxne_js></div>
			<div class=hebxbne_left-div-2>
				<h2 style="text-align:left">JavaScript排行</h2>
				<ul>
					
					<li><a class="font7 nleft" title="移動端網頁自適應縮放方案:Viewport 與響應式佈局實戰" href="https://twcomputer.wsxdn.com/programming/scripttopics/javascript/201510/68334.html">移動端網頁自適應縮放方案:Viewport 與響應式佈局實戰</a></li>
					
					<li><a class="font7 nleft" title="AngularJS 動畫實戰指南:ngAnimate 與 JavaScript …" href="https://twcomputer.wsxdn.com/programming/scripttopics/javascript/201510/68259.html">AngularJS 動畫實戰指南:ngAnimate 與 JavaScript …</a></li>
					
					<li><a class="font7 nleft" title="JavaScript Math.abs() 方法完全指南:獲取絕對值" href="https://twcomputer.wsxdn.com/programming/scripttopics/javascript/201510/68312.html">JavaScript Math.abs() 方法完全指南:獲取絕對值</a></li>
					
					<li><a class="font7 nleft" title="JavaScript 捕獲鍵盤按鍵:`key`、`code`、`keyCode`…" href="https://twcomputer.wsxdn.com/programming/scripttopics/javascript/201510/68827.html">JavaScript 捕獲鍵盤按鍵:`key`、`code`、`keyCode`…</a></li>
					
					<li><a class="font7 nleft" title="HTML button 默認 type=submit 導致表單誤提交問題" href="https://twcomputer.wsxdn.com/programming/scripttopics/javascript/201510/70514.html">HTML button 默認 type=submit 導致表單誤提交問題</a></li>
					
				</ul>
			</div>
			
			
			
			<div class=kenbxne_js></div>
		</div>
		<div class="nright hebxbne_right">
			<div class=guanggao1 id=guanggao_r1></div>
			<div class=kenbxne_js></div>
			<div class=hebxbne_right-div1>
				<h2>推薦文章</h2>
				<div class=kenbxne_js></div>
				<ul class=hebxbne_right-list1> 

					<li><a class="font7 nleft" title="2015 年 JavaScript 生態趨勢:擁抱庫、遠離框架" href="https://twcomputer.wsxdn.com/programming/scripttopics/javascript/201510/69813.html">2015 年 JavaScript 生態趨勢:擁抱庫、遠離框架</a></li>
					
					<li><a class="font7 nleft" title="ExtJS 瀏覽器類型檢測源碼解析(極致兼容寫法)" href="https://twcomputer.wsxdn.com/programming/scripttopics/javascript/201510/70881.html">ExtJS 瀏覽器類型檢測源碼解析(極致兼容寫法)</a></li>
					
					<li><a class="font7 nleft" title="JavaScript 實現網頁表格自動縮放與變色特效(經典舊碼解析)" href="https://twcomputer.wsxdn.com/programming/scripttopics/javascript/201510/69552.html">JavaScript 實現網頁表格自動縮放與變色特效(經典舊碼解析)</a></li>
					
					<li><a class="font7 nleft" title="JavaScript String.prototype.localeCompar…" href="https://twcomputer.wsxdn.com/programming/scripttopics/javascript/201510/68404.html">JavaScript String.prototype.localeCompar…</a></li>
					
					<li><a class="font7 nleft" title="JavaScript prompt() 回傳值處理完整指南:型別、預設值與實務應…" href="https://twcomputer.wsxdn.com/programming/scripttopics/javascript/201510/69837.html">JavaScript prompt() 回傳值處理完整指南:型別、預設值與實務應…</a></li>
					
					<li><a class="font7 nleft" title="jQuery 獲取控件值完全指南:三大類方法、ASP.NET 控件特殊處理與最佳…" href="https://twcomputer.wsxdn.com/programming/scripttopics/javascript/201510/70823.html">jQuery 獲取控件值完全指南:三大類方法、ASP.NET 控件特殊處理與最佳…</a></li>
					
					<li><a class="font7 nleft" title="JavaScript String 對象完全指南:創建、方法與最佳實踐" href="https://twcomputer.wsxdn.com/programming/scripttopics/javascript/201510/68323.html">JavaScript String 對象完全指南:創建、方法與最佳實踐</a></li>
					
					<li><a class="font7 nleft" title="多個 Checkbox 選中時判斷是否包含特定值的實用邏輯" href="https://twcomputer.wsxdn.com/programming/scripttopics/javascript/201510/69987.html">多個 Checkbox 選中時判斷是否包含特定值的實用邏輯</a></li>
					
					<li><a class="font7 nleft" title="AngularJS ng-options 指令完全指南:下拉選單綁定、分組、自定…" href="https://twcomputer.wsxdn.com/programming/scripttopics/javascript/201510/68275.html">AngularJS ng-options 指令完全指南:下拉選單綁定、分組、自定…</a></li>
					
					<li><a class="font7 nleft" title="JavaScript 核心語法速查 106 條:從基礎到 DOM、BOM、事件、…" href="https://twcomputer.wsxdn.com/programming/scripttopics/javascript/201510/72357.html">JavaScript 核心語法速查 106 條:從基礎到 DOM、BOM、事件、…</a></li>
					
 </ul>
			</div>
			
		</div>
		<div class=kenbxne_js></div>
	</div>
	<div class=kenbxne_js></div>
	<div class=plnebxmj>
	<div class="plnebxmj-2 flink">
		<h2><a class=bottom href="https://twcomputer.wsxdn.com/" target=_blank>萬盛學電腦網</a>| <a class=bottom hreflang="ja" href="https://jp.wsxdn.com/" target=_blank>日本語版</a> | <a class=bottom onclick="this.style.behavior='url(#default#homepage)';this.sethomepage('https://twcomputer.wsxdn.com');" href="#">設為首頁</a> | <a class=bottom href="javascript:window.external.addfavorite('https://twcomputer.wsxdn.com','萬盛學電腦網');">加入收藏</a></h2>
	</div>
	<div class=knemnnx></div>
</div>

<div class="ojwbxnks">copyright © <a title="萬盛學電腦網" href="https://twcomputer.wsxdn.com/" target=_blank>萬盛學電腦網</a> all rights reserved  
	<br>
</div>

 </div>
</body>
</html>