轉載作者:小新。
https://m.yisu.com/zixun/446969.html
javascript中將xml轉換為json字符串的方法:首先通過XML字符串或請求XML文件來獲取XML的DOM對象;然后通過遍歷和遞歸來獲取子元素的nodeValue值;最后拼接出JSON字符串即可。
利用JavaScript將XML轉換為JSON。
首先通過XML字符串來生成XML的DOM對象:
/**
* 通過傳入xml的內容字符串來解析xml
* @param xmlString xml字符串
* @returns xml的Document對象
*/
function getXmlDocumentByXmlString(xmlString) {
var xmlDoc = null;
if (window.DOMParser) {
var parser = new DOMParser();
xmlDoc = parser.parseFromString(xmlString, "text/xml");
} else {
//IE
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(xmlString);
}
return xmlDoc;
}
或者通過請求XML文件來獲取XML的DOM對象:
/**
* 通過傳入xml文件路徑來解析xml文檔
* @param xmlFilePath xml文檔路徑,如:files/test.xml
* @returns xml的Document對象
*/
function getXmlDocumentByFilePath(xmlFilePath) {
//xmlDocument對象
var xmlDoc = null;
//xmlhttp對象
var xmlhttp = null;
if (window.XMLHttpRequest) {
//IE7+, FireFox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
//IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", xmlFilePath, false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
return xmlDoc;
}
接下來就是重點的部分了,通過遍歷和遞歸獲取子元素的nodeValue,來拼接出JSON字符串,實現將XML轉換成JSON字符串:
/**
* 將XML的Document對象轉換為JSON字符串
* @param xmlDoc xml的Document對象
* @return string
*/
function convertToJSON(xmlDoc) {
//准備JSON字符串和緩存(提升性能)
var jsonStr = "";
var buffer = new Array();
buffer.push("{");
//獲取xml文檔的所有子節點
var nodeList = xmlDoc.childNodes;
generate(nodeList);
/**
* 中間函數,用於遞歸解析xml文檔對象,並附加到json字符串中
* @param node_list xml文檔的的nodeList
*/
function generate(node_list) {
for (var i = 0; i < node_list.length; i++) {
var curr_node = node_list[i];
//忽略子節點中的換行和空格
if (curr_node.nodeType == 3) {
continue;
}
//如果子節點還包括子節點,則繼續進行遍歷
if (curr_node.childNodes.length > 1) {
buffer.push("\"" + curr_node.nodeName + "\": {");
generate(curr_node.childNodes);
} else {
var firstChild = curr_node.childNodes[0];
if (firstChild != null) {
//nodeValue不為null
buffer.push("\"" + curr_node.nodeName + "\":\"" + firstChild.nodeValue + "\"");
} else {
//nodeValue為null
buffer.push("\"" + curr_node.nodeName + "\":\"\"");
}
}
if (i < (node_list.length - 2)) {
buffer.push(",");
} else {
break;
}
}
//添加末尾的"}"
buffer.push("}");
}
jsonStr = buffer.join("");
return jsonStr;
}
使用方式:通過getXmLDocumentByFilePath(xmlFilePath)或者getXmlDocumentByXmlString(xmlString)獲取XML的Document對象,然后通過調用convertToJSON(xmlDocument)傳入xml的Ducument對象即可得到轉換后的JSON字符串。
適用范圍:不含有attribute的任意XML文檔。