开发者

check if xml node does not exist and do something instead of failing

Given the following XML.

<?xml version="1.0" encoding="UTF-8"?>
<xmldata>
   <Products>
       <ProductCode>M406789</ProductCode>
       <ProductID>858</ProductID>
       <ProductName>M406789 Ignition Box</ProductName>
       <ProductDescriptionShort>&lt;img alt="" src="/v/vspfiles/assets/images/alliance_small.jpg" align="right" /&gt;Ignition Box</ProductDescriptionShort>
       <ListPrice>134.2200</ListPrice>
       <ProductPrice>80.5300</ProductPrice>
       <SalePrice>59.9500</SalePrice>
   </Products>
</xmldata>

This is the relevant part of a script.

Set xNewDoc = xData.responseXML 'ResponseXml returns DOMDocument object

Set ProductCode = xNewDoc.SelectSingleNode("//ProductCode")
Set ListPrice = xNewDoc.SelectSingleNode("//ListPrice")

x=Len(开发者_开发技巧ListPrice.Text)
newlp = Left(ListPrice.Text,x-2)

Set ProductPrice = xNewDoc.SelectSingleNode("//ProductPrice")
x=Len(ProductPrice.Text)
newpp = Left(ProductPrice.Text,x-2)

Set SalePrice = xNewDoc.SelectSingleNode("//SalePrice")
x=Len(SalePrice.Text)
newsp = Left(SalePrice.Text,x-2)

Set ProductName = xNewDoc.SelectSingleNode("//ProductName")

If the above xml that is loaded is missing and of the nodes (lets say "SalePrice") the script will fail. How can I test to see if the node exists so it doesn't fail. I saw something on this on Stack in the past but can't seem to find it.


After setting getting a node from the XML, apply an Is Nothing check around the rest:

newpp = 0 'Initialize with a default value
Set ProductPrice = xNewDoc.SelectSingleNode("//ProductPrice")
If Not ProductPrice Is Nothing Then
    x=Len(ProductPrice.Text)
    newpp = Left(ProductPrice.Text,x-2)
End If


You can just do an If Not ... Is Nothing check every time you use the variable, like so:

Set ListPrice = xNewDoc.SelectSingleNode("//ListPrice")

If Not ListPrice Is Nothing Then
    x=Len(ListPrice.Text)
    newlp = Left(ListPrice.Text,x-2)
End If

Set ProductPrice = xNewDoc.SelectSingleNode("//ProductPrice")

If Not ProductPrice Is Nothing Then
    x=Len(ProductPrice.Text)
    newpp = Left(ProductPrice.Text,x-2)
End If


Take the element as a list:

Dim xmlNodeList As MSXML2.IXMLDOMNodeList

Set xmlNodeList = xNewDoc.selectNodes("//ProductPrice")

Now ask for the length of the list. If zero there was none.

debug.print xmlNodeList.length
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜