jquery - How to get xml data

后端 未结 2 1109
一个人的身影
一个人的身影 2021-02-19 03:05

Im a total noob to html, css, javascript, and programming altogether. Please bear with me.

Im trying to populate my table using jquery. The data will be coming from an x

2条回答
  •  别跟我提以往
    2021-02-19 03:52

    I was in similar problem, where I was fetching XML data using HTTP GET and then parsing. Taking your example:

    $.ajax({
        type: "GET",
        url: "football_player.xml",
        ->dataType: "text",
        success: function(xml) {
            var parser = new DOMParser();
            var xmlDoc = parser.parseFromString(xml, "text/xml");
            var json = ->getJson(xmlDoc);
            for(var i =0; i< json[0].football_player.length;i++) {
                var player = json[0].football_player[i];
                $("table tbody").append("");
                $("table tbody").append("" + ->player.name + "");
                $("table tbody").append("" + ->player.club + "");
                $("table tbody").append("" + ->player.number + "");
                $("table tbody").append("" + ->player.country + "");
                $("table tbody").append("");
            }
        }
    });
    

    Three things to notice (->):

    1. dataType: "text" I made http request with data type as TEXT rather than XML, so that I get xml data as a string data type.

    2. getJson(xmlDoc) method: I wrote a small function to convert XML to Javascript object (JSON). There are other small utilities available to do the same.

    3. player.name: due to this conversion, you can use XML content as javascript objects and thus easier to parse and read.

    I am pasting getJson() function below (its not tested, I made it for a POC, but worked for me):

    function getJson(xmlDoc) {
        var result = [];
    
        for (var i = 0; i < xmlDoc.children.length; i++) {
            var child = xmlDoc.children[i];
            if (result[child.tagName] === undefined) {
                result[child.tagName] = [];
            }
    
            var nodeJson = getJsonFromNode(xmlDoc.children[i]);
            result[child.tagName].push(nodeJson);
        }
    
        return result;
    }
    
    function getJsonFromNode(node) {
        var nodeJson = {};
        // for attributes
        for (var i = 0; i < node.attributes.length; i++) {
            var att = node.attributes[i];
            nodeJson[att.localName] = att.value;
        }
    
        // for child nodes
        for (var i = 0; i < node.children.length; i++) {
            var child = node.children[i];
            if (nodeJson[child.tagName] === undefined) {
                nodeJson[child.tagName] = [];
            }
            var result = getJsonFromNode(node.children[i]);
            nodeJson[child.tagName].push(result);
        }
    
        return nodeJson;
    }
    

提交回复
热议问题