> JSON中文在线手册 > JavaScript将XML转成JSON的方法

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结果:

代码如下:
{
  "@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转换成XML后,对应的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 >'+
					'<iframe src="' + url + '" scrolling="auto"  ></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>[email protected]</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中调用XML数据</title>
</head>
<body bgcolor="#FFFFFF">
<b>标题: </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>