Como analisar a resposta do serviço da web xml usando Javascript ou jQuery
-
28-10-2019 - |
Pergunta
Desejo usar o seguinte serviço da web xml. www.musicbrainz.org/ws/2/artist/?query= artist: michael jackson
qual formato é como abaixo:
<metadata><artist-list offset="0" count="3418"><artist ext:score="100" type="Person" id="f27ec8db-af05-4f36-916e-3d57f91ecf5e"><name>Michael Jackson</name><sort-name>Jackson, Michael</sort-name><gender>male</gender><country>US</country>
Eu só quero analisar este xml e obter o gênero dele. Usei o seguinte código para analisar o xml. Aqui eu obtenho o atributo ext do artista, mas não funciona.
$.ajax({
type: 'GET',
url: 'http://www.musicbrainz.org/ws/2/artist/?query=artist:michael jackson',
dataType: 'xml',
success: function(xml){
// console.log(xml);
$(xml).find('artist-list').each(function(){
$(this).find('artist').each(function(){
var ext = $(this).attr('ext');
alert(ext);
});
});
}
});
Qualquer pessoa pode me sugerir o exemplo para analisar xml usando Javascript ou jQuery.
Solução
$.ajax({
type: 'GET',
url: 'http://www.musicbrainz.org/ws/2/artist/?query=artist:michael jackson',
dataType: 'xml',
success: function(xml){
$("artist", xml).each(function(){
console.log($("gender", this).text());
});
}
});
<✓Atualizar:
Acabei de verificar o serviço da web e vi que nem todo artist
tem uma tag gender
especificada.Nesse caso, você pode usar o seguinte:
$("artist", xml).each(function(){
var gender = $("gender", this);
if(gender.length>0)
console.log($(gender).text());
});
Veja JSFiddle Demo aqui.
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow