XML的经典ASP - 空值

时间:2015-04-08 21:15:04

标签: xml asp-classic

我有以下经典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>

我道歉,因为我确信这很容易,但如何防止错误发生呢?我是否检查该值是否为空?我是否以不同的方式获取值?

谢谢。

瑞克

1 个答案:

答案 0 :(得分:0)

firstChild.nodeValue要求firstChild属性不为null,因为null没有nodeValue属性。

避免该错误的更简单方法是使用innerText代替firstChild.nodeValue

strSearchState = objLst(0).getElementsByTagName("adminArea3")(0).innerText