這篇文章將為大家詳細講解有關javascript中將xml轉為json的方法,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
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文檔。
關于“javascript中將xml轉為json的方法”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。