Como ler o conteúdo do arquivo xml em jQuery e mostrar em elementos html?

Sou novo na Jquery.Estou a tentar ler dados do " sampleXML.arquivo xml e exibir esses dados em elementos Html "li". até agora eu tenho feito é, eu criei arquivo html da seguinte forma:nome do arquivo-"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>
E esta é a minha .ficheiro js:

$(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);
            }
        }
    });
});

O Meu ficheiro xml é o seguinte:

<?xml version='1.0' ?>
<doc>
  <person>
    <name>sachin</name>
    <age>21</age>
  </person>
  <person>
    <name>Akash</name>
    <age>18</age>
  </person>
</doc>
Mas isto não funciona. Preciso de ligar um ficheiro externo para"$.Forum" . Por isso, por favor, diz-me onde estou a cometer erros . . obrigado antecipadamente . .

Author: Manoj Sharma, 2013-10-07

7 answers

Acho que queres assim., demonstração
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>');

});
 29
Author: Rishi Php, 2015-03-28 02:57:27

Simplesmente você pode ler o ficheiro XML como dataType: "xml", ele irá reutilizar o objecto xml já processado. você pode usá-lo como objeto jquery e encontrar qualquer coisa ou loop jogá-lo...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>');  
    }); 
    }       
});
});

Documentos JQuery para parseXML

 16
Author: Chris Charles, 2017-01-03 12:14:56

Em Primeiro Lugar, criar em Arquivo e, em seguida, converter os seus dados xml em array e recuperar esses dados no formato json para a resposta de sucesso ajax.

Tentar como em baixo:

$(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
            }                
        }
    });
});  

Amostra.php

$xml = "YOUR XML FILE PATH";
$json = json_encode((array)simplexml_load_string($xml)),1);
echo $json;
 1
Author: Dhaval Bharadva, 2013-10-07 09:30:13

Pode usar $.each()

Suponha que o seu xml é

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

Na tua Ajax success

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

Para o seu caso

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();
        });
    }
 1
Author: Ajith S, 2013-10-07 09:43:45

O texto de resposta é o que procura. Exemplo:

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

Onde o xml é o teu ficheiro. Lembre-se que este será o seu xml na forma de uma string. Você pode analisá-lo usando xmlparse como alguns deles mencionados.

 1
Author: Revanth Kumar, 2015-04-24 01:02:00

 $.get("/folder_name/filename.xml", function (xml) {
 var xmlInnerhtml = xml.documentElement.innerHTML;
 });
 0
Author: sakthi sudhan, 2018-11-01 12:23:25

Obter o XML usando a chamada Ajax, encontrar o elemento principal, circular por todo o elemento e adicionar dados na tabela.

Código da amostra

 //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>');
                });
            }
        });

Ligação de violino: https://jsfiddle.net/pn9xs8hf/2/

Fonte: leia XML usando o jQuery e carregue-o na tabela HTML

 0
Author: Vikas Lalwani, 2020-08-31 11:45:27