将xml转换为json并格式化

时间:2014-07-14 04:32:09

标签: javascript xml json

我正在使用CTA API(http://www.transitchicago.com/developers/bustracker.aspx) 并且响应是xml。在我收集骨干系列后,我想转换为json。响应如下:

<?xml version="1.0"?>
<bustime-response>
<route>
    <rt>1</rt>
    <rtnm>Bronzeville/Union Station</rtnm>
    <rtclr>#336633</rtclr>
</route>        
<route>
    <rt>2</rt>
    <rtnm>Hyde Park Express</rtnm>
    <rtclr>#993366</rtclr>
</route>        
</bustime-response>

我希望它看起来像这样:

[
  {
    "rt": "1",
    "rtnm": "Bronzeville/Union Station",
    "rtclr": "#336633"
  },
  {
    "rt": "2",
    "rtnm": "Hyde Park Express",
    "rtclr": "#993366"
  }
]

最好的方法是什么?

1 个答案:

答案 0 :(得分:0)

试试这个功能,它对我有用:

xmlToJson = function(xml) {
var obj = {};
if (xml.nodeType == 1) {                
    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) { 
    obj = xml.nodeValue;
}            
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;
 }

 var jsonText = JSON.stringify(xmlToJson(xmlDoc)); 

有关详细信息,请查看以下链接

http://davidwalsh.name/convert-xml-json