JavaScript實現(xiàn)的XML與JSON互轉(zhuǎn)功能詳解
本文實例講述了JavaScript實現(xiàn)的XML與JSON互轉(zhuǎn)功能。分享給大家供大家參考,具體如下:
這里來分享一個關(guān)于JavaScript實現(xiàn)XML與JSON互轉(zhuǎn)例子,這里面介紹了國外的三款xml轉(zhuǎn)json的例子,希望這些例子能給你帶來幫助。
最近在開發(fā)在線XML編輯器,打算使用JSON做為中間格式。因為JSON相對于XML,有著容易閱讀、解析速度快、占用空間小等優(yōu)點,更易于在WEB上傳遞數(shù)據(jù)。但在實際使用中還是發(fā)現(xiàn)了一些易于忽略的細(xì)節(jié),對于需要嚴(yán)格保證XML原始結(jié)構(gòu)的情況,在轉(zhuǎn)換成JSON時需要一些注意。
XML轉(zhuǎn)換成JSON的格式大概如下:
XML形式
<article> <header id="h1"> 文章標(biāo)題 </header> <section id="s1"> <header> 章節(jié)標(biāo)題 </header> <p> 章節(jié)段落 </p> </section> </article>
JSON表現(xiàn)形式
{
"article": {
"header": {
"#text": "文章標(biāo)題",
"@id": "h1"
},
"section": {
"@id": "s1",
"header": "章節(jié)標(biāo)題",
"p": "章節(jié)段落"
}
}
}
用Js將XML轉(zhuǎn)換成JSON的腳本,在網(wǎng)上找了一些現(xiàn)成的腳本,但大都只滿足比較簡單的情況,都不可以完成保證原始結(jié)構(gòu)的互轉(zhuǎn)。下面是從網(wǎng)上找到的一些腳本或者文章:
x2js : https://code.google.com/p/x2js/
jsonxml :http://davidwalsh.name/convert-xml-json
JKL.ParseXML :http://www.kawa.net/works/js/jkl/parsexml-e.html
x2js不會將下面的XML正確還原。
//XML形式 <p> <strong>章節(jié)</strong>段<em>落</em> </p>
而第2個腳本jsonxml,在上面這種“文本混合標(biāo)簽”的情況下,沒有將標(biāo)簽提取出來,而是轉(zhuǎn)換成了下面這種格式。
{"p":"<strong>章節(jié)</strong>段<em>落</em>"}}
之后我做了些改動,將它解析成如下格式后,滿足了“文本混合標(biāo)簽”可正確還原的情況。
{"p":[{"strong":"章節(jié)"},"段",{"em":"落"}]}
另外,形如下面的代碼,使用上文提到的腳本進行轉(zhuǎn)換,也會導(dǎo)致無法正確還原的情況。
<article> <section id="s1">第一節(jié)</section> <header id="h1"> 標(biāo)題 </header> <section id="s2">第二節(jié)</section> </article>
同樣,在一個標(biāo)簽內(nèi),它的子標(biāo)簽出現(xiàn)了大于一次,如果需要記錄數(shù)據(jù)的路徑,應(yīng)該使用數(shù)組來保存這個結(jié)構(gòu)。正確的代碼應(yīng)該是:
{
"article": [ {
"section": {
"#text": "第一節(jié)",
"@id": "s1"
},
}, {
"header": {
"#text": "標(biāo)題",
"@id": "h1"
}
}, {
"section": {
"#text": "第一節(jié)",
"@id": "s2"
}
}
]
}
jkl.parsexml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <items> <item> <zip_cd>10036</zip_cd> <us_state>NY</us_state> <us_city>New York</us_city> <us_dist>Broadway</us_dist> </item> </items>
SAMPLE SCRIPT:
<script type="text/javascript" src="jkl-parsexml.js"></script> <script><!-- var url = "zip-e.xml"; var xml = new JKL.ParseXML( url ); var data = xml.parse(); document.write( data["items"]["item"]["us_state"] ); document.write( data.items.item.us_state ); // --></script>
OUTPUT JSON:
{
items: {
item: {
zip_cd: "1000001"
us_state: "NY",
us_city: "New York",
us_dist: "Broadway",
}
}
};
jsonxml
// 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].push) == "undefined") {
var old = obj[nodeName];
obj[nodeName] = [];
obj[nodeName].push(old);
}
obj[nodeName].push(xmlToJson(item));
}
}
}
return obj;
};
The major change I needed to implement was using attributes.item(j) instead of the attributes[j] that most of the scripts I found used. With this function, XML that looks like:
<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>
...becomes workable a JavaScript object with the following structure:
{
"@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
}
}
}
]
}
說了半天下面整理了一個例子
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;
};
PS:這里再為大家提供幾款關(guān)于xml與json操作的在線工具供大家參考使用:
在線XML/JSON互相轉(zhuǎn)換工具:
http://tools.jb51.net/code/xmljson
在線格式化XML/在線壓縮XML:
http://tools.jb51.net/code/xmlformat
XML在線壓縮/格式化工具:
http://tools.jb51.net/code/xml_format_compress
在線JSON代碼檢驗、檢驗、美化、格式化工具:
http://tools.jb51.net/code/json
JSON在線格式化工具:
http://tools.jb51.net/code/jsonformat
在線json壓縮/轉(zhuǎn)義工具:
http://tools.jb51.net/code/json_yasuo_trans
更多關(guān)于JavaScript相關(guān)內(nèi)容可查看本站專題:《JavaScript中ajax操作技巧總結(jié)》、《JavaScript操作XML文件技巧總結(jié)》、《JavaScript中json操作技巧總結(jié)》、《JavaScript錯誤與調(diào)試技巧總結(jié)》及《JavaScript數(shù)據(jù)結(jié)構(gòu)與算法技巧總結(jié)》
希望本文所述對大家JavaScript程序設(shè)計有所幫助。
- JQuery的ajax獲取數(shù)據(jù)后的處理總結(jié)(html,xml,json)
- C# XML與Json之間相互轉(zhuǎn)換實例詳解
- JQuery解析HTML、JSON和XML實例詳解
- xml轉(zhuǎn)json的js代碼
- 對比分析json及XML
- JavaScript將XML轉(zhuǎn)成JSON的方法
- JSON與XML優(yōu)缺點對比分析
- json跟xml的對比分析
- 如何在JS中實現(xiàn)相互轉(zhuǎn)換XML和JSON
- JavaScript原生xmlHttp與jquery的ajax方法json數(shù)據(jù)格式實例
- js實現(xiàn)的xml對象轉(zhuǎn)json功能示例
- JSON與XML的區(qū)別對比及案例應(yīng)用
相關(guān)文章
JS構(gòu)造函數(shù)與原型prototype的區(qū)別介紹
下面小編就為大家?guī)硪黄狫S構(gòu)造函數(shù)與原型prototype的區(qū)別介紹。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-07-07
JavaScript函數(shù)執(zhí)行、作用域鏈以及內(nèi)存管理詳解
這篇文章主要介紹了JavaScript函數(shù)執(zhí)行、作用域鏈以及內(nèi)存管理的知識,文章內(nèi)容非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-01-01
JS?getRandomValues和Math.random方法深入解析
這篇文章主要為大家介紹了JS?getRandomValues和Math.random方法深入詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-04-04
es6基礎(chǔ)學(xué)習(xí)之解構(gòu)賦值
解構(gòu)賦值語法是一個 Javascript 表達(dá)式,這使得可以將值從數(shù)組或?qū)傩詮膶ο筇崛〉讲煌淖兞恐?。這篇文章主要給大家介紹了關(guān)于es6基礎(chǔ)學(xué)習(xí)之解構(gòu)賦值的相關(guān)資料,需要的朋友可以參考下2018-12-12

