我有以下经典ASP代码:
Set objXMLHTTP = Server.CreateObject("MSXML2.ServerXMLHTTP")
URL="The link to the XML source goes here"
objXMLHTTP.Open "GET", URL, false
objXMLHTTP.Send
strHTML = objXMLHTTP.responseText
'Load the XML File
Set objXML = Server.CreateObject("Microsoft.XMLDOM")
objXML.async = False
objXML.loadXML(strHTML)
Set objLst = objXML.getElementsByTagName("result")
strSearchCity = objLst(0).getElementsByTagName("adminArea5")(0).firstchild.nodeValue
strSearchState = objLst(0).getElementsByTagName("adminArea3")(0).firstchild.nodeValue
这是一个可以正常运行的XML的剪辑:
<response>
<info>
</info>
<results>
<result>
<providedLocation>
<location>chicago, il</location>
</providedLocation>
<locations>
<location>
<adminArea5 type="City">Chicago</adminArea5>
<adminArea3 type="State">IL</adminArea3>
<adminArea4 type="County">Cook County</adminArea4>
</location>
</locations>
</result>
</results>
</response>
但是,如果其中一个返回null,我会收到错误。
<location>
<adminArea5 type="City">Washington</adminArea5>
<adminArea3 type="State"/>
</location>
我道歉,因为我确信这很容易,但如何防止错误发生呢?我是否检查该值是否为空?我是否以不同的方式获取值?
谢谢。
瑞克
答案 0 :(得分:0)
firstChild.nodeValue
要求firstChild
属性不为null,因为null
没有nodeValue
属性。
避免该错误的更简单方法是使用innerText
代替firstChild.nodeValue
:
strSearchState = objLst(0).getElementsByTagName("adminArea3")(0).innerText