本文實例講述了JavaScript實現的XML與JSON互轉功能。分享給大家供大家參考,具體如下:
這里來分享一個關于JavaScript實現XML與JSON互轉例子,這里面介紹了國外的三款xml轉json的例子,希望這些例子能給你帶來幫助。
最近在開發在線XML編輯器,打算使用JSON做為中間格式。因為JSON相對于XML,有著容易閱讀、解析速度快、占用空間小等優點,更易于在WEB上傳遞數據。但在實際使用中還是發現了一些易于忽略的細節,對于需要嚴格保證XML原始結構的情況,在轉換成JSON時需要一些注意。
XML轉換成JSON的格式大概如下:
XML形式
<article><header id="h1"> 文章標題 </header><section id="s1"><header> 章節標題 </header><p> 章節段落 </p></section></article>
JSON表現形式
{"article": {"header": {"#text": "文章標題","@id": "h1"},"section": {"@id": "s1","header": "章節標題","p": "章節段落"}}}
用Js將XML轉換成JSON的腳本,在網上找了一些現成的腳本,但大都只滿足比較簡單的情況,都不可以完成保證原始結構的互轉。下面是從網上找到的一些腳本或者文章:
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>章節</strong>段<em>落</em> </p>
而第2個腳本jsonxml,在上面這種“文本混合標簽”的情況下,沒有將標簽提取出來,而是轉換成了下面這種格式。
{"p":"<strong>章節</strong>段<em>落</em>"}}
之后我做了些改動,將它解析成如下格式后,滿足了“文本混合標簽”可正確還原的情況。
{"p":[{"strong":"章節"},"段",{"em":"落"}]}
另外,形如下面的代碼,使用上文提到的腳本進行轉換,也會導致無法正確還原的情況。
<article> <section id="s1">第一節</section> <header id="h1"> 標題 </header> <section id="s2">第二節</section></article>
同樣,在一個標簽內,它的子標簽出現了大于一次,如果需要記錄數據的路徑,應該使用數組來保存這個結構。正確的代碼應該是:
{ "article": [ { "section": { "#text": "第一節", "@id": "s1" }, }, { "header": { "#text": "標題", "@id": "h1" } }, { "section": { "#text": "第一節", "@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 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].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 objectvar obj = {};if (xml.nodeType == 1) { // element// do attributesif (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) { // textobj = xml.nodeValue;}// do childrenif (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:這里再為大家提供幾款關于xml與json操作的在線工具供大家參考使用:
在線XML/JSON互相轉換工具:
http://tools.VeVB.COm/code/xmljson
在線格式化XML/在線壓縮XML:
http://tools.VeVB.COm/code/xmlformat
XML在線壓縮/格式化工具:
http://tools.VeVB.COm/code/xml_format_compress
在線JSON代碼檢驗、檢驗、美化、格式化工具:
http://tools.VeVB.COm/code/json
JSON在線格式化工具:
http://tools.VeVB.COm/code/jsonformat
在線json壓縮/轉義工具:
http://tools.VeVB.COm/code/json_yasuo_trans
更多關于JavaScript相關內容可查看本站專題:《JavaScript中ajax操作技巧總結》、《JavaScript操作XML文件技巧總結》、《JavaScript中json操作技巧總結》、《JavaScript錯誤與調試技巧總結》及《JavaScript數據結構與算法技巧總結》
希望本文所述對大家JavaScript程序設計有所幫助。
新聞熱點
疑難解答