JavaScript將XML轉(zhuǎn)成JSON的方法

2022-05-17 14:31 更新

1. JavaScript代碼如下:

// Changes XML to JSON
function xmlToJson(xml) {
    // Create the return object
    var obj = {};
    if (xml.nodeType == 1) { // element
        // do attributes
        if (xml.attributes.length > 0) {
        obj["@attributes"] = {};
            for (var j = 0; j < xml.attributes.length; j++) {
                var attribute = xml.attributes.item(j);
                obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
            }
        }
    } else if (xml.nodeType == 3) { // text
        obj = xml.nodeValue;
    }
    // do children
    if (xml.hasChildNodes()) {
        for(var i = 0; i < xml.childNodes.length; i++) {
            var item = xml.childNodes.item(i);
            var nodeName = item.nodeName;
            if (typeof(obj[nodeName]) == "undefined") {
                obj[nodeName] = xmlToJson(item);
            } else {
                if (typeof(obj[nodeName].length) == "undefined") {
                    var old = obj[nodeName];
                    obj[nodeName] = [];
                    obj[nodeName].push(old);
                }
                obj[nodeName].push(xmlToJson(item));
            }
        }
    }
    return obj;
};
2. XML代碼:
<ALEXA VER="0.9" URL="davidwalsh.name/" HOME="0" AID="=">
    <SD TITLE="A" FLAGS="" HOST="davidwalsh.name">
        <TITLE TEXT="David Walsh Blog :: PHP, MySQL, CSS, Javascript, MooTools, and Everything Else"/>
        <LINKSIN NUM="1102"/>
        <SPEED TEXT="1421" PCT="51"/>
    </SD>
    <SD>
        <POPULARITY URL="davidwalsh.name/" TEXT="7131"/>
        <REACH RANK="5952"/>
        <RANK DELTA="-1648"/>
    </SD>
</ALEXA>
3. JSON結(jié)果:
{
  "@attributes": {
    AID: "=",
    HOME:  0,
    URL: "davidwalsh.name/",
    VER: "0.9",
  },
  SD = [
    {
      "@attributes": {
        FLAGS: "",
        HOST: "davidwalsh.name",
        TITLE: A
      },
      LINKSIN: {
        "@attributes": {
          NUM: 1102
        }
      },
      SPEED: {
        "@attributes": {
          PCT: 51,
          TEXT: 1421
        }
      },
      TITLE: {
        "@attributes": {
          TEXT: "David Walsh Blog :: PHP, MySQL, CSS, Javascript, MooTools, and Everything Else",
        }
      },
    },
    {
      POPULARITY: {
        "@attributes": {
          TEXT: 7131,
          URL: "davidwalsh.name/"
        }
      },
      RANK: {
        "@attributes": {
          DELTA: "-1648"
        }
      },
      REACH: {
        "@attributes": {
          RANK = 5952
        }
      }
    }
  ]
}
例子:

json轉(zhuǎn)換成XML后,對(duì)應(yīng)的JS文件要怎么改?

$(function() {
		
	$('#logout').click(function(){
		top.location.href = "../login.html";
	});
		
	$("#tree").tree( {
		url : "../data/menu.json",
		onClick : doMenuClick
	});

	function doMenuClick(node) {
		if ($("#tree").tree("isLeaf", node.target) == false)
			return;

		var id = node.id;
		var text = node.text;
		if (!id) return;
				
		var elTab = parent.$('#mainTabs'); 
		if (elTab.tabs('exists', text)) {
			elTab.tabs('select', text);
		} else {
			var url = '../TheReport/' + id + '.html';
			var content = '<div style="width:100%;height:100%;overflow:hidden;">'+
					'<iframe src="' + url + '" scrolling="auto" style="width:100%;height:100%;border:0;" ></iframe></div>';

			elTab.tabs('add', {
				title : text,
				content : content,
				closable : true
			});
		}
	}
});
上面的menu.json文件改成menu.xml文件后,這些代碼需要改的什么?

答案:

<?xml version="1.0" encoding="GB2312"?>
<myfile>
    <title>tttt</title>
    <author>ajie</author>
    <email>ajie@aolhoo.com</email>
    <date>20010115</date>
</myfile>

HTML/JS:

<html>
<head>
<script language="JavaScript" for="window" event="onload">
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.load("myfile.xml");
root = xmlDoc.documentElement;
//nodes = xmlDoc.documentElement.childNodes;
document.all("title").innerText = root.childNodes.item(0).text;
document.all("author").innerText = root.childNodes.item(1).text;
document.all("email").innerText = root.childNodes.item(2).text;
document.all("date").innerText = root.childNodes.item(3).text;
</script>
<title>在HTML中調(diào)用XML數(shù)據(jù)</title>
</head>
<body bgcolor="#FFFFFF">
<b>標(biāo)題: </b>
<span id="title"> </span>
<b>作者: </b>
<span id="author"></span>
<b>信箱: </b>
<span id="email"></span>
<b>日期:</b>
<span id="date"></span>
</body>
</html>
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)