我从Lightroom导出了一个Flash网页库。它使用XML文件显示每张照片的标题。我想要的是从这个XML文件中提取描述标记,以便我可以将它发送到校对者。我一直在尝试使用javascript来做到这一点,但它只是不起作用。我的代码能够让我得到所有描述的部分列表。我的代码遍历描述标记但是一旦遇到空标记:它(使用Chrome调试器)抛出未捕获的TypeError:无法读取null 的属性'data'并停止执行。 我试图检查“null!==”,但我猜测代码仍在运行,因为我仍然得到错误。
到目前为止,我确信XML是邪恶的。
XML文件示例:
<?xml version="1.0" encoding="ISO-8859-1"?>
<mediaGroup>
<amgVersion version="1.3" />
<groupInfo>
<bunch of="data I don't care about" />
</groupInfo>
<sizes>
<bunch of="data I don't care about" />
</sizes>
<media totalGallerySize="104">
<item>
<title></title>
<description>Yo! Look at that monkey on the bars</description>
<imageID />
<mediaType/>
<renditions>
<rendition size="large" />
<rendition size="medium" />
<rendition size="small" />
<rendition size="thumb" />
</renditions>
</item>
<item>
<title></title>
<description>It's trying to parse XML files ahhaha</description>
<imageID />
<mediaType/>
<renditions>
<rendition size="large" />
<rendition size="medium" />
<rendition size="small" />
<rendition size="thumb" />
</renditions>
</item>
<item>
<title></title>
<description></description>
<imageID />
<mediaType/>
<renditions>
<rendition size="large" />
<rendition size="medium" />
<rendition size="small" />
<rendition size="thumb" />
</renditions>
</item>
<item>
<title></title>
<description>That missing description is going to make him angry</description>
<imageID />
<mediaType/>
<renditions>
<rendition size="large" />
<rendition size="medium" />
<rendition size="small" />
<rendition size="thumb" />
</renditions>
</item>
</mediaGroup>
对于我的代码,我有以下内容:
<script type="text/javascript">
function loadXMLDoc(dname) {
if (window.XMLHttpRequest)
{
xhttp=new XMLHttpRequest();
}
else
{
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",dname,false);
xhttp.send();
return xhttp.responseXML;
} //end function
xmlDoc=loadXMLDoc("group.xml");
var z=xmlDoc.getElementsByTagName("item"), nameELEM;
document.write(z.length);
for (i=0;i<=z.length;i++){
nameELEM=z[i].getElementsByTagName("description")[0];
if (typeof nameELEM.firstChild.data !== "undefined") { //This is the line the error quotes
//handle property xxx of documentFragment as required
document.write(nameELEM.firstChild.data + "<br />");
}
}
</script>
第38行:未捕获的TypeError:无法读取null的属性“data” 第38行= if(typeof nameELEM.firstChild.data!==“undefined”){
答案 0 :(得分:2)
而不是:
if (nameELEM.firstChild.data !== null)
尝试:
if (typeof nameELEM.firstChild.data !== "undefined"
)