我需要一种方法来检查XML节点值是空还是空,因为如果任何节点出现空,我的代码就会失败。
<!-- Get Playlist XML from radio_info dir -->
function getPlaylist() {
$.ajax({
type: "GET",
url: radioPath, // ** Set path to radio_info XML here **
cache: false,
dataType: "xml",
error: function(jqXHR, textStatus, errorThrown) {
alert("error:" + errorThrown );
},
success: nowPlaying
//nowPlaying found the XML and retreived it
});
};
//nowPlaying gets vars from xml on getPlaylist success
var stationid = xml.getElementsByTagName("stationid")[0].childNodes[0].nodeValue;
var currentdate = xml.getElementsByTagName("currentdate"[0].childNodes[0].nodeValue;
var artist = xml.getElementsByTagName("artist")[0].childNodes[0].nodeValue;
var title = xml.getElementsByTagName("title")[0].childNodes[0].nodeValue;
var album = xml.getElementsByTagName("album")[0].childNodes[0].nodeValue;
var year = xml.getElementsByTagName("year")[0].childNodes[0].nodeValue;
var pStart= xml.getElementsByTagName("timestamp")[0].childNodes[0].nodeValue;
var duration = xml.getElementsByTagName("duration")[0].childNodes[0].nodeValue;
var type = xml.getElementsByTagName("type")[0].childNodes[0].nodeValue;
var artfile = xml.getElementsByTagName("artfile")[0].childNodes[0].nodeValue;
var currentfile = xml.getElementsByTagName("currentfile")[0].childNodes[0].nodeValue;
var recent1 = xml.getElementsByTagName("recent1")[0].childNodes[0].nodeValue;
var recent2 = xml.getElementsByTagName("recent2")[0].childNodes[0].nodeValue;
var recent3 = xml.getElementsByTagName("recent3")[0].childNodes[0].nodeValue;
var recent4 = xml.getElementsByTagName("recent4")[0].childNodes[0].nodeValue;
如果上述任何一个变量看到我的xml中的空节点,则代码会中断。
示例XML代码:
<?xml version="1.0" encoding="ISO-8859-1"?>
<event>
<station>
<stationid><![CDATA[MIKE'S FAMOUS RADIO]]></stationid>
<currenttime><![CDATA[7:30 pm]]></currenttime>
<currentdate><![CDATA[January 06, 2014]]></currentdate>
</station>
<song>
<artist><![CDATA[Spirit]]></artist>
<title><![CDATA[I Got a Line on You]]></title>
<album><![CDATA[The Family That Plays Together]]></album>
<timestamp>7:30 pm</timestamp>
<duration>02:38</duration>
<type><![CDATA[MUSIC]]></type>
<url><![CDATA[]]></url>
<year>1968</year>
<genre><![CDATA[Rock]]></genre>
<cdfile><![CDATA[505-13]]></cdfile>
<copyright><![CDATA[]]></copyright>
<composer><![CDATA[California]]></composer>
<publisher><![CDATA[Hollenbeck]]></publisher>
<comments><![CDATA[]]></comments>
<artfile><![CDATA[The Family That Plays Together.jpg]]></artfile>
<currentfile><![CDATA[505-13]]></currentfile>
</song>
<recent>
<recent1><![CDATA[7:26 pm - Talking Heads - Take Me to the River (1978)]]></recent1>
<recent2><![CDATA[<!--BSIRECENTX2-->]]></recent2>
<recent3><![CDATA[<!--BSIRECENTX3-->]]></recent3>
<recent4><![CDATA[<!--BSIRECENTX4-->]]></recent4>
</recent>
</event>
每次歌曲结束时都会重新生成xml,有时会为某个节点提供值
答案 0 :(得分:1)
我更喜欢使用jQuery遍历来查找值
var $xml = $(xml);
var stationid = $xml.find('stationid').text();
正如我在评论中所说,它可能比本机dom遍历慢,但除非处理100个记录,否则它应该不是问题。它大大增加了代码的可读性