[javascript] How to read xml file contents in jQuery and display in html elements?

I am new to Jquery.I am trying to read data from "sampleXML.xml" file and display that data in Html "li" elements. so far I have done is, I have created html file as follows:file name-"Cloudtags.html":

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script>
    <script  src=Cloudtags.js></script>
    <title>Css Globe: tag clouds</title>
    <link rel="stylesheet" type="text/css" href="Cloudtags.css">
    <script type="text/javascript" src="js/jquery.js"></script>

</head>

<body>

<div id="container">    
    <script type="text/javascript" src="http://cssglobe.com/ads/blogsponsor.js"></script>

    <div id="side">
        <div class="tags">
            <ul class="cld">
                <li class="tag1" id="java"><a href="https://www.google.com">google</a></li> 
                <li class="tag2"><a href="#">Chiessy</a></li>
                <li class="tag3"><a href="#">sitemap</a></li>
                <li class="tag2"><a href="#">Sales</a></li>
                <li class="tag4" ><a href="#">Gohome</a></li>
                <li class="tag1"id="temp"><a href="#">Movies</a></li>
                <li class="tag1"><a href="#">It Jobz</a></li>
                <li class="tag5"><a href="#">Alza</a></li>
                <li class="tag2"><a href="#">Sea food</a></li>
                <li class="tag1"><a href="#">Hospital</a></li>
                <li class="tag3"><a href="#">Smart phone</a></li>
                <li class="tag4"><a href="#">Pizza </a></li>
                <li class="tag1"><a href="#">Aerobics</a></li>
                <li class="tag5"><a href="#">Yahoo...</a></li>
                <li class="tag1"><a href="#">Anti-Virus</a></li>
                <li class="tag2"><a href="#">Travel</a></li>
            </ul>
        </div>
    </div>

    <div id="xmldata"></div>

</div><br>
</body>
</html>

and this is my .js file:

$(document).ready(function() {
    var nm;
    $.ajax({
        type: "GET" ,
        url: "sampleXML.xml" ,
        dataType: "xml" ,
        success: function(xml) {
            $(xml).find('person').each(function() {
                nm= $(this).text()
                $("#temp").html(nm);
            }
        }
    });
});

My xml file is as follows:

<?xml version='1.0' ?>
<doc>
  <person>
    <name>sachin</name>
    <age>21</age>
  </person>
  <person>
    <name>Akash</name>
    <age>18</age>
  </person>
</doc>

But this does not work. Do I need to link some external file for "$.ajax" . So ,please tell me where I'm making mistake . . thanks in advance . .

This question is related to javascript jquery html

The answer is


Get the XML using Ajax call, find the main element, loop through all the element and append data in table.

Sample code

 //ajax call to load XML and parse it
        $.ajax({
            type: 'GET',
            url: 'https://res.cloudinary.com/dmsxwwfb5/raw/upload/v1591716537/book.xml',           // The file path.
            dataType: 'xml',    
            success: function(xml) {
               //find all book tags, loop them and append to table body
                $(xml).find('book').each(function() {
                    
                    // Append new data to the tbody element.
                    $('#tableBody').append(
                        '<tr>' +
                            '<td>' +
                                $(this).find('author').text() + '</td> ' +
                            '<td>' +
                                $(this).find('title').text() + '</td> ' +
                            '<td>' +
                                $(this).find('genre').text() + '</td> ' +
                                '<td>' +
                                $(this).find('price').text() + '</td> ' +
                                '<td>' +
                                $(this).find('description').text() + '</td> ' +
                        '</tr>');
                });
            }
        });

Fiddle link: https://jsfiddle.net/pn9xs8hf/2/

Source: Read XML using jQuery & load it in HTML Table


First of all create on file and then convert your xml data in array and retrieve that data in json format for ajax success response.

Try as below:

$(document).ready(function () {
    $.ajax({
        type: "POST",
        url: "sample.php",            
        success: function (response) {
            var obj = $.parseJSON(response);
            for(var i=0;i<obj.length;i++){
                // here you can add html through loop
            }                
        }
    });
});  

sample.php

$xml = "YOUR XML FILE PATH";
$json = json_encode((array)simplexml_load_string($xml)),1);
echo $json;

_x000D_
_x000D_
 $.get("/folder_name/filename.xml", function (xml) {_x000D_
 var xmlInnerhtml = xml.documentElement.innerHTML;_x000D_
 });
_x000D_
_x000D_
_x000D_


responseText is what you are looking for. Example:

    $.ajax({
...
complete: function(xhr, status) {
alert(xhr.responseText);
}
});

Where xml is your file. Remember this will be your xml in the form form of a string. You can parse it using xmlparse as some of them mentioned.


Simply you can read XML file as dataType: "xml", it will retuen xml object already parsed. you can use it as jquery object and find anything or loop throw it…etc.

$(document).ready(function(){
   $.ajax({
    type: "GET" ,
    url: "sampleXML.xml" ,
    dataType: "xml" ,
    success: function(xml) {

    //var xmlDoc = $.parseXML( xml );   <------------------this line
    //if single item
    var person = $(xml).find('person').text();  

    //but if it's multible items then loop
    $(xml).find('person').each(function(){
     $("#temp").append('<li>' + $(this).text() + '</li>');  
    }); 
    }       
});
});

jQuery docs for parseXML


I think you want like this, DEMO

var xmlDoc = $.parseXML( xml ); 

var $xml = $(xmlDoc);

var $person = $xml.find("person");

$person.each(function(){

    var name = $(this).find('name').text(),
        age = $(this).find('age').text();

    $("#ProfileList" ).append('<li>' +name+ ' - ' +age+ '</li>');

});

You can use $.each()

Suppose your xml is

<Cloudtags><id>1</id></Cloudtags><Cloudtags><id>2</id></Cloudtags><Cloudtags><id>3</id></Cloudtags>

In your Ajax success

success: function (xml) {
    $(xml).find('Cloudtags').each(function(){// your outer tag of xml
         var id = $(this).find("id").text(); // 
    });
}

For your case

success: function (xml) {
        $(xml).find('person').each(function(){// your outer tag of xml
             var name = $(this).find("name").text(); // 
             var age = $(this).find("age").text();
        });
    }

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment