Domanda

Sto creando un Yahoo! Widget e lo hai già fatto senza problemi (creazione di un widget). Ricevo un documento xml tramite un collegamento Web e voglio ottenere tutti i nodi in un albero. Sto facendo questo:

var request = new XMLHttpRequest();
        request.open( "GET", url, false );
        request.send();
        if ( request.status == 200 )
        {
            doc = request.responseXML;
            tree = doc.evaluate("/lfm");
            status = tree.item(0).getAttribute("status")
            if(status == "ok")
            {
                print ("status is ok!");
                tracks = doc.evaluate("/lfm/recenttracks[1]/track");
                for(i=0;i<tracks.length;i++)
                {
                    artist = tracks.item(i).firstChild.firstChild.data;
                }
            }
        }
    }

In questo modo puoi estrarre il nodo artista dall'albero . c'è un problema però se si desidera avere il fratello successivo . Devi chiamare

tracks.item(i).firstChild.nextSibling.firstChild.data;
tracks.item(i).firstChild.nextSibling.nextSibling.firstChild.data;
tracks.item(i).firstChild.nextSibling.nextSibling.nextSibling.firstChild.data;

per farlo. Il nodo accanto a questo aggiunge un 'nextsibling' e così via. Non voglio continuare ad aggiungere questi nodi e ho pensato che sarebbe stato possibile utilizzare childNodes [i] in questo modo:

artist = tracks.item(i).childNodes[0].firstChild.data;
nextitem = tracks.item(i).childNodes[1].firstChild.data;

questo non funziona però. restituisce " childNodes [0] non ha proprietà " in qualunque modo lo utilizzi. Ora penso che ci sia anche un modo in Xpath per farlo in un for-loop:

name = doc.evaluate("string(/lfm/recenttracks[1]/track["+i+"]/name)");
                    print(name);
othernode = doc.evaluate("string(/lfm/recenttracks[1]/track["+i+"]/album)");
                    print(othernode);

e quindi aumentando i per la traccia successiva. ma in qualche modo questo restituisce solo un elemento . non recupera più elementi in un per -loop. Anche i-1 non funziona.

Qualcuno sa come usare un'espressione Xpath con il mio valore i per scegliere un nodo e quindi ottenere i nodi secondari per supernodo? Per traccia voglio ottenere artista, nome, streaming, mbid, album, url, immagine (piccola), immagine (media), immagine (grande) e data.

il mio file xml è simile al seguente:

<lfm status="ok">
   <recenttracks user="xaddict">
      <track nowplaying="true"> 
         <artist mbid="f5b8ea5f-c269-45dd-9936-1fedf3c56851">The Presets</artist>
         <name>Girl (You Chew My Mind Up)</name>
         <streamable>1</streamable>
         <mbid></mbid>
         <album mbid="b150d099-b0f3-4feb-9a05-34e693c6dd24">Beams</album>
         <url>http://www.last.fm/music/The+Presets/_/Girl+%28You+Chew+My+Mind+Up%29</url>
         <image size="small">http://userserve-ak.last.fm/serve/34s/8696437.jpg</image>
         <image size="medium">http://userserve-ak.last.fm/serve/64s/8696437.jpg</image>
         <image size="large">http://userserve-ak.last.fm/serve/126/8696437.jpg</image>
         <date uts="1236440600">7 Mar 2009, 15:43</date>
      </track>
      <track > 
         <artist mbid="f5b8ea5f-c269-45dd-9936-1fedf3c56851">The Presets</artist>
         <name>Get Outta Here</name>
         <streamable>1</streamable>
         <mbid></mbid>
         <album mbid="0469956f-d895-4120-8ec5-29ad41b9e2fd">Blow Up</album>
         <url>http://www.last.fm/music/The+Presets/_/Get+Outta+Here</url>
         <image size="small">http://userserve-ak.last.fm/serve/34s/20923179.png</image>
         <image size="medium">http://userserve-ak.last.fm/serve/64s/20923179.png</image>
         <image size="large">http://userserve-ak.last.fm/serve/126/20923179.png</image>
         <date uts="1236440242">7 Mar 2009, 15:37</date>
      </track>
   </recenttracks>
</lfm>
È stato utile?

Soluzione 3

il modo completamente abilitato per Xpath di fare ciò sta usando la conversione di stringhe in Xpath. Ho già pubblicato questo codice come risposta a un'altra domanda e lo farò di nuovo. Sono molto contento di aver scoperto questo modo di fare le cose.

var entries = xmlDoc.evaluate("lfm/recenttracks/track");
var length = entries.length;
for(var i = 0; i &lt; length; i++) {
   var entry = entries.item(i);
   var obj = {
      artist: entry.evaluate("string(artist)"),
      name: entry.evaluate("string(name)"),
      url: entry.evaluate("string(url)"),
      image: entry.evaluate("string(image[@size='medium'])")
   };
posts[i] = obj;
}

Altri suggerimenti

Prova questo

 for (var i = 0; i < xmlDoc.getElementsByTagName('track').length; i++)
            {
                alert(xmlDoc.getElementsByTagName('track')[i].getElementsByTagName('name')[0].childNodes[0].nodeValue); 
            }

se vuoi usare xpath, puoi anche provare la soluzione qui sotto.

var s = xmlDoc.evaluate( '//track' ,xmlDoc, null, XPathResult.ANY_TYPE, null );
var track = s.iterateNext();

while (track)
{
     alert(track.getElementsByTagName('name')[0].textContent );
     track = s.iterateNext();
}

Puoi pubblicare il frammento XML rilevante? Stiamo esaminando il tuo codice che lo analizza, ma se avessimo l'XML stesso, sarebbe più semplice consultare una query Xpath. Il più utile sarebbe il bit che ha elementi come

<lfm>
    <recenttracks>
        <track>
            <album>

etc

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top