Home  >  Article  >  Web Front-end  >  JavaScript method to convert XML to JSON_javascript skills

JavaScript method to convert XML to JSON_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:09:541480browse

The example in this article describes how JavaScript converts XML to JSON. Share it with everyone for your reference. The specific method is as follows:

1. The JavaScript code is as follows:

Copy code The code is as follows:
// 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 code:
Copy code The code is as follows:


             <br>            <LINKSIN NUM="1102"/><br>            <SPEED TEXT="1421" PCT="51"/><br> </SD><br> <SD><br>             <POPULARITY URL="davidwalsh.name/" TEXT="7131"/><br>            <REACH RANK="5952"/><br>            <RANK DELTA="-1648"/><br> </SD><br> </ALEXA></div> <br> 3. JSON result: <br> <div class="codetitle"> <span><a style="CURSOR: pointer" data="35638" class="copybut" id="copybut35638" onclick="doCopy('code35638')"><u>Copy code</u></a></span> The code is as follows:</div> <div class="codebody" id="code35638">{<br>   "@attributes": {<br>     AID: "=",<br>     HOME:  0,<br>     URL: "davidwalsh.name/",<br>     VER: "0.9",<br>   },<br>   SD = [<br>     {<br>       "@attributes": {<br>         FLAGS: "",<br>         HOST: "davidwalsh.name",<br>         TITLE: A<br>       },<br>       LINKSIN: {<br>         "@attributes": {<br>           NUM: 1102<br>         }<br>       },<br>       SPEED: {<br>         "@attributes": {<br>           PCT: 51,<br>           TEXT: 1421<br>         }<br>       },<br>       TITLE: {<br>         "@attributes": {<br>           TEXT: "David Walsh Blog :: PHP, MySQL, CSS, Javascript, MooTools, and Everything Else",<br>         }<br>       },<br>     },<br>     {<br>       POPULARITY: {<br>         "@attributes": {<br>           TEXT: 7131,<br>           URL: "davidwalsh.name/"<br>         }<br>       },<br>       RANK: {<br>         "@attributes": {<br>           DELTA: "-1648"<br>         }<br>       },<br>       REACH: {<br>         "@attributes": {<br>           RANK = 5952<br>         }<br>       }<br>     }<br>   ]<br> }</div> <p>关于js操作xml感兴趣的朋友还可参考在线工具:</p> <p><a target="_blank" href="http://tools.jb51.net/code/xmljson">在线XML/JSON互相转换工具</a><br> </p> <p><a target="_blank" href="http://tools.jb51.net/code/xmlformat">在线XML格式化/压缩工具</a><br> </p> <p>希望本文所述对大家的javascript程序设计有所帮助。</p></div><div class="nphpQianMsg"><div class="clear"></div></div><div class="nphpQianSheng"><span>Statement:</span><div>The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn</div></div></div><div class="nphpSytBox"><span>Previous article:<a class="dBlack" title="JavaScript methods and techniques to check whether pop-up windows are blocked_javascript techniques" href="http://m.php.cn/faq/8467.html">JavaScript methods and techniques to check whether pop-up windows are blocked_javascript techniques</a></span><span>Next article:<a class="dBlack" title="JavaScript methods and techniques to check whether pop-up windows are blocked_javascript techniques" href="http://m.php.cn/faq/8469.html">JavaScript methods and techniques to check whether pop-up windows are blocked_javascript techniques</a></span></div><div class="nphpSytBox2"><div class="nphpZbktTitle"><h2>Related articles</h2><em><a href="http://m.php.cn/article.html" class="bBlack"><i>See more</i><b></b></a></em><div class="clear"></div></div><ul class="nphpXgwzList"><li><b></b><a href="http://m.php.cn/faq/1609.html" title="An in-depth analysis of the Bootstrap list group component" class="aBlack">An in-depth analysis of the Bootstrap list group component</a><div class="clear"></div></li><li><b></b><a href="http://m.php.cn/faq/1640.html" title="Detailed explanation of JavaScript function currying" class="aBlack">Detailed explanation of JavaScript function currying</a><div class="clear"></div></li><li><b></b><a href="http://m.php.cn/faq/1949.html" title="Complete example of JS password generation and strength detection (with demo source code download)" class="aBlack">Complete example of JS password generation and strength detection (with demo source code download)</a><div class="clear"></div></li><li><b></b><a href="http://m.php.cn/faq/2248.html" title="Angularjs integrates WeChat UI (weui)" class="aBlack">Angularjs integrates WeChat UI (weui)</a><div class="clear"></div></li><li><b></b><a href="http://m.php.cn/faq/2351.html" title="How to quickly switch between Traditional Chinese and Simplified Chinese with JavaScript and the trick for websites to support switching between Simplified and Traditional Chinese_javascript skills" class="aBlack">How to quickly switch between Traditional Chinese and Simplified Chinese with JavaScript and the trick for websites to support switching between Simplified and Traditional Chinese_javascript skills</a><div class="clear"></div></li></ul></div></div><footer><div class="footer"><div class="footertop"><img src="/static/imghwm/logo.png" alt=""><p>Public welfare online PHP training,Help PHP learners grow quickly!</p></div><div class="footermid"><a href="http://m.php.cn/about/us.html">About us</a><a href="http://m.php.cn/about/disclaimer.html">Disclaimer</a><a href="http://m.php.cn/update/article_0_1.html">Sitemap</a></div><div class="footerbottom"><p> © php.cn All rights reserved </p></div></div></footer><script>isLogin = 0;</script><script type="text/javascript" src="/static/layui/layui.js"></script><script type="text/javascript" src="/static/js/global.js?4.9.47"></script></div><script src="https://vdse.bdstatic.com//search-video.v1.min.js"></script><link rel='stylesheet' id='_main-css' href='/static/css/viewer.min.css' type='text/css' media='all'/><script type='text/javascript' src='/static/js/viewer.min.js?1'></script><script type='text/javascript' src='/static/js/jquery-viewer.min.js'></script><script>jQuery.fn.wait = function (func, times, interval) { var _times = times || -1, //100次 _interval = interval || 20, //20毫秒每次 _self = this, _selector = this.selector, //选择器 _iIntervalID; //定时器id if( this.length ){ //如果已经获取到了,就直接执行函数 func && func.call(this); } else { _iIntervalID = setInterval(function() { if(!_times) { //是0就退出 clearInterval(_iIntervalID); } _times <= 0 || _times--; //如果是正数就 -- _self = $(_selector); //再次选择 if( _self.length ) { //判断是否取到 func && func.call(_self); clearInterval(_iIntervalID); } }, _interval); } return this; } $("table.syntaxhighlighter").wait(function() { $('table.syntaxhighlighter').append("<p class='cnblogs_code_footer'><span class='cnblogs_code_footer_icon'></span></p>"); }); $(document).on("click", ".cnblogs_code_footer",function(){ $(this).parents('table.syntaxhighlighter').css('display','inline-table');$(this).hide(); }); $('.nphpQianCont').viewer({navbar:true,title:false,toolbar:false,movable:false,viewed:function(){$('img').click(function(){$('.viewer-close').trigger('click');});}}); </script></body></html>