Movatterモバイル変換


[0]ホーム

URL:


codecamp

JavaScript将XML转成JSON的方法

1. JavaScript代码如下:

// Changes XML to JSONfunction 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>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中调用XML数据</title></head><body bgcolor="#FFFFFF"><b>标题: </b><span> </span><b>作者: </b><span></span><b>信箱: </b><span></span><b>日期:</b><span></span></body></html>
JavaScript中字符串(string)转json的方法
java与javascript之间json格式数据互转介绍
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录
关于 JSON

JSON 教程

JSON 基础

json格式

JSON 示例

JSON解析

JSON遍历

JSON调用

JSON转换

JSON获取

JSON字符串

JSON数组

关闭

MIP.setData({'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false},'pageFontSize' : getCookie('pageFontSize') || 20});MIP.watch('pageTheme', function(newValue){setCookie('pageTheme', JSON.stringify(newValue))});MIP.watch('pageFontSize', function(newValue){setCookie('pageFontSize', newValue)});function setCookie(name, value){var days = 1;var exp = new Date();exp.setTime(exp.getTime() + days*24*60*60*1000);document.cookie = name + '=' + value + ';expires=' + exp.toUTCString();}function getCookie(name){var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)');return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null;}
[8]ページ先頭

©2009-2025 Movatter.jp