使用Javascript,Jquery将XML转换为Json对象

时间:2013-12-19 10:28:15

标签: javascript json xml

我需要将xml转换为json。

我的XML数据是:

<fl val="A_Value">AAAAAAAAAA</fl>
<fl val="B_Value">
  <![CDATA["BBBBBBBB"]]>
</fl>
<fl val="C_Value">CCCCCCCCCC</fl>
<fl val="D_Value">DDDDDDDDDD</fl>

我想将此转换为json:

{
   AAAAAAAAAA : A_Value,
   BBBBBBBB   : B_Value,
   CCCCCCCCCC : C_Value,
   DDDDDDDDDD : D_Value
}

任何人都可以帮助我。感谢。

2 个答案:

答案 0 :(得分:2)

我们从字符串中的XML数据开始:

    import java.util.Arrays;
    import javafx.application.Application;
    import javafx.collections.FXCollections;
    import javafx.scene.Scene;
    import javafx.scene.chart.CategoryAxis;
    import javafx.scene.chart.NumberAxis;
    import javafx.scene.chart.StackedBarChart;
    import javafx.scene.chart.XYChart;
    import javafx.stage.Stage;

    public class HorizontalHistogramTest extends Application{


        final static String austria = "Austria";
        final static String brazil = "Brazil";
        final static String france = "France";
        final static String italy = "Italy";
        final static String usa = "USA";
        final CategoryAxis xAxis = new CategoryAxis();
        final NumberAxis yAxis = new NumberAxis();
        final StackedBarChart<Number, String> sbc =
        new StackedBarChart<Number,String>(yAxis, xAxis);
        final XYChart.Series<Number,String> series1 =
        new XYChart.Series<Number,String>();

@Override
public void start(Stage stage) {
    stage.setTitle("Bar Chart Sample");
    sbc.setTitle("Country Summary");
    xAxis.setLabel("Country");
    xAxis.setCategories(FXCollections.<String>observableArrayList(
            Arrays.asList(austria, brazil, france, italy, usa)));
    yAxis.setLabel("Percent");
    // plus value
    series1.getData().add(new XYChart.Data<Number,String>(10, austria));
    series1.getData().add(new XYChart.Data<Number,String>(50, brazil));
    series1.getData().add(new XYChart.Data<Number,String>(40, france));
    series1.getData().add(new XYChart.Data<Number,String>(50, italy));
    series1.getData().add(new XYChart.Data<Number,String>(60, usa));
    // minus value
    series1.getData().add(new XYChart.Data<Number,String>(-90, austria));
    series1.getData().add(new XYChart.Data<Number,String>(-50, brazil));
    series1.getData().add(new XYChart.Data<Number,String>(-60, france));
    series1.getData().add(new XYChart.Data<Number,String>(-50, italy));
    series1.getData().add(new XYChart.Data<Number,String>(-40, usa));

    Scene scene = new Scene(sbc, 800, 600);
    sbc.getData().addAll(series1);
    stage.setScene(scene);
    stage.show();
}

public static void main(String[] args) {
    launch(args);
}
}

将字符串转换为XML doc object

var xmlStr = 
  '<root><fl val="A_Value">AAAAAAAAAA</fl>' + 
  '<fl val="B_Value">' + 
  '  <![CDATA["BBBBBBBB"]]>' + 
  '</fl>' + 
  '<fl val="C_Value">CCCCCCCCCC</fl>' + 
  '<fl val="D_Value">DDDDDDDDDD</fl></root>';

然后convert the XML doc object to JSON

var parseXml;

if (window.DOMParser) {
    parseXml = function(xmlStr) {
        return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml");
    };
} else if (typeof window.ActiveXObject != "undefined" && new window.ActiveXObject("Microsoft.XMLDOM")) {
    parseXml = function(xmlStr) {
        var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        xmlDoc.loadXML(xmlStr);
        return xmlDoc;
    };
} else {
    parseXml = function() { return null; }
}

var xmlDoc = parseXml(xmlStr);

然后将对象转换为所需的结构:

function xmlToJson(xml) {
    // Create the return object
    var obj = {};

    // console.log(xml.nodeType, xml.nodeName );

    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 || 
             xml.nodeType == 4) { // text and cdata section
        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);
                }
                if (typeof(obj[nodeName]) === 'object') {
                    obj[nodeName].push(xmlToJson(item));
                }
            }
        }
    }
    return obj;
}

var theJson = xmlToJson(xmlDoc);
console.log(JSON.stringify(theJson));
/*
"{"root":{"fl":[{"@attributes":{"val":"A_Value"},"#text":{}},{"@attributes":{"val":"B_Value"},"#text":{},"#cdata-section":"\"BBBBBBBB\""},{"@attributes":{"val":"C_Value"},"#text":{}},{"@attributes":{"val":"D_Value"},"#text":{}}]}}"
*/

答案 1 :(得分:1)

XML to JSON Plugin(jQuery.xml2json)是一个可用于将简单XML转换为JSON对象的脚本。它会对你有所帮助。