一个实用的 Javascript XML to JSON Object 对象的转换 (JQuery)

一个实用的 Javascript XML to JSON  Object 对象的转换 (JQuery)

一个用来将xml文件转换成对象的插件

xml文件如下
<?xml version="1.0" encoding="UTF-8" ?>
<root>
<content>
  <plugins>TreeView</plugins>
  <plugins>ListGrid</plugins>
  <plugins>ListBox</plugins>
</content>
<pool>1</pool>
</root>

生成的对象为:



调用

var xml = $.loadXML("PluginConf.xml");
var obj = $(xml).toObject().get(0);
alert(obj.pool);

以下是 源码下载

/* *
 * 转换xml为对象形式
 * @return {Object}
 * @param {XMLHttpRequest} elXML
 
*/
$.fn.toObject 
=   function  (){
    
if  ( this == null return   null ;
    
var  retObj  =   new  Object;
    buildObjectNode(retObj,
/* jQuery */ this .get( 0 ));
    
return  $(retObj);
    
function  buildObjectNode(cycleOBJ, /* Element */ elNode){
        
/* NamedNodeMap */
        
var  nodeAttr = elNode.attributes;
        
if (nodeAttr  !=   null ){
            
if  (nodeAttr.length && cycleOBJ == null ) cycleOBJ = new  Object; 
            
for ( var  i = 0 ;i < nodeAttr.length;i ++ ){
                cycleOBJ[nodeAttr[i].name]
= nodeAttr[i].value;
            }
        }
        
var  nodeText = " text " ;
        
if  (elNode.text == null ) nodeText = " textContent " ;
        
/* NodeList */
        
var  nodeChilds = elNode.childNodes;
        
if (nodeChilds != null ){
            
if  (nodeChilds.length && cycleOBJ == null ) cycleOBJ = new  Object; 
            
for ( var  i = 0 ;i < nodeChilds.length;i ++ ){
                
if  (nodeChilds[i].tagName != null ){
                    
if  (nodeChilds[i].childNodes[ 0 ] != null && nodeChilds[i].childNodes.length <= 1 && (nodeChilds[i].childNodes[ 0 ].nodeType == 3 || nodeChilds[i].childNodes[ 0 ].nodeType == 4 )){
                        
if  (cycleOBJ[nodeChilds[i].tagName] == null ){
                            cycleOBJ[nodeChilds[i].tagName]
= nodeChilds[i][nodeText];
                        }
else {
                            
if  ( typeof (cycleOBJ[nodeChilds[i].tagName]) == " object " && cycleOBJ[nodeChilds[i].tagName].length){
                                cycleOBJ[nodeChilds[i].tagName][cycleOBJ[nodeChilds[i].tagName].length]
= nodeChilds[i][nodeText];
                            }
else {
                                cycleOBJ[nodeChilds[i].tagName]
= [cycleOBJ[nodeChilds[i].tagName]];
                                cycleOBJ[nodeChilds[i].tagName][
1 ] = nodeChilds[i][nodeText];
                            }
                        }
                    }
else {
                        
if  (nodeChilds[i].childNodes.length){
                            
if  (cycleOBJ[nodeChilds[i].tagName] == null ){
                                cycleOBJ[nodeChilds[i].tagName]
= new  Object;
                                buildObjectNode(cycleOBJ[nodeChilds[i].tagName],nodeChilds[i]);
                            }
else {
                                
if  (cycleOBJ[nodeChilds[i].tagName].length){
                                    cycleOBJ[nodeChilds[i].tagName][cycleOBJ[nodeChilds[i].tagName].length]
= new  Object;
                                    buildObjectNode(cycleOBJ[nodeChilds[i].tagName][cycleOBJ[nodeChilds[i].tagName].length
- 1 ],nodeChilds[i]);
                                }
else {
                                    cycleOBJ[nodeChilds[i].tagName]
= [cycleOBJ[nodeChilds[i].tagName]];
                                    cycleOBJ[nodeChilds[i].tagName][
1 ] = new  Object;
                                    buildObjectNode(cycleOBJ[nodeChilds[i].tagName][
1 ],nodeChilds[i]);
                                }
                            }
                        }
else {
                            cycleOBJ[nodeChilds[i].tagName]
= nodeChilds[i][nodeText];
                        }
                    }
                }
            }
        }
    }
}

/* *
 * @return {Element}
 * @param {String} _url
 
*/
$.loadXML 
=   function  (_url){
    
var  ret;
    $.ajax({
          type:
" get " ,
          url:_url,
        async:
false ,
          dataType:
" xml " ,
        success:
function (xml){
            ret 
=  xml;
        }
      });
    
return  ret.documentElement;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: jQuery 提供了一个方法 `$.parseXML()`,用于将字符串形式的 XML 解析成 XML Document 对象。这样就可以使用 jQuery 的 DOM 操作方法来遍历解析出来的 XML 了。 举个例子: ``` $.ajax({ type: "GET", url: "data.xml", dataType: "xml", success: function(xml) { // 将 XML 解析为 XML Document 对象 var xmlDoc = $.parseXML(xml), $xml = $(xmlDoc); // 使用 jQuery 的 DOM 操作方法来遍历解析出来的 XML $xml.find("item").each(function() { var $this = $(this), item = {}; item.title = $this.find("title").text(); item.description = $this.find("description").text(); // 将解析出来的数据存入数组 items.push(item); }); } }); ``` 然后,就可以使用 `JSON.stringify()` 将遍历出来的数据转为 JSON 字符串了。 举个例子: ``` var jsonString = JSON.stringify(items); ``` 最后,就可以使用 `JSON.parse()` 将 JSON 字符串转为 JSON 对象了。 举个例子: ``` var items = JSON.parse(jsonString); ``` 这样就完成了将 XML 数据转为 JSON 数据的过程。 ### 回答2: 使用jQuery可以将XML数据转换JSON数据。首先,我们需要获取XML数据并将其加载到一个变量中,然后使用jQuery的方法将其转换JSON格式。以下是一个示例代码: ```javascript // 获取XML数据 var xmlData = '<root><name>John Doe</name><age>25</age><city>New York</city></root>'; // 将XML数据转换JSON格式 var jsonData = $.xml2json(xmlData); // 输出转换后的JSON数据 console.log(jsonData); ``` 上述代码中,我们使用了一个虚拟的XML数据,你需要将其替换为实际的XML数据。然后,通过调用`$.xml2json`方法将XML数据转换JSON格式,并将结果保存在`jsonData`变量中。最后,我们使用`console.log`方法输出转换后的JSON数据。 需要注意的是,jQuery本身不提供将XML转换JSON的功能,我们可以使用第三方库`jquery.xml2json`来实现这个功能。你可以在引入`jquery.xml2json`插件后使用`$.xml2json`方法来实现XMLJSON的功能。 最后,值得一提的是,使用jQueryXML转换JSON的功能并不是一种常见的需求,因为XMLJSON具有不同的数据结构和用途。如果可能的话,推荐直接使用JSON格式数据,以避免进行额外的转换过程。 ### 回答3: 使用jQuery可以很方便地将XML数据转换JSON数据。 首先,需要用`$.ajax`方法来读取XML文件。其中,`dataType`属性设置为`xml`,表示读取的数据为XML格式。 然后,在`success`回调函数中,可以使用`$.parseXML`方法来解析XML数据,将其转换为一个DOM对象。 接下来,可以使用jQuery的选择器来获取XML中的各个节点,并将其转换JSON格式。例如,可以使用`$(domObject).find`方法来获取XML中的节点,再使用`.each`方法遍历节点。 在遍历每个节点时,可以使用`node.nodeName`获取节点名称,`node.textContent`获取节点的文本内容,并将其组织成一个JSON对象。 最后,可以使用`JSON.stringify`方法将JSON对象转换JSON字符串,并将其输出。 以下是一个示例代码: ```javascript $.ajax({ url: "data.xml", dataType: "xml", success: function(xml) { var json = []; $(xml).find('node').each(function() { var node = {}; node.name = $(this).attr('name'); node.content = $(this).text(); json.push(node); }); var jsonString = JSON.stringify(json); console.log(jsonString); } }); ``` 以上代码假设要转换XML路径为"data.xml",XML中的节点名称为"node",节点属性名为"name",节点内容为文本。 使用这段代码,XML数据将会被转换JSON数据,并输出到控制台中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值