Cómo analizar la respuesta del servicio web XML usando Javascript o jQuery
-
28-10-2019 - |
Pregunta
Quiero utilizar el siguiente servicio web xml. www.musicbrainz.org/ws/2/artist/?query= artist: michael jackson
cuyo formato es el siguiente:
<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>
Solo quiero analizar este xml y obtener el género. Usé el siguiente código para analizar xml. Aquí obtengo el atributo ext del artista pero no 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);
});
});
}
});
Cualquiera puede sugerirme el ejemplo para analizar XML usando Javascript o jQuery.
Solución
$.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());
});
}
});
<”Actualización:
Acabo de revisar el servicio web y vi que no todos los artist
tienen una etiqueta gender
especificada.En este caso, puede utilizar lo siguiente:
$("artist", xml).each(function(){
var gender = $("gender", this);
if(gender.length>0)
console.log($(gender).text());
});
Consulte JSFiddle Demo aquí.
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow