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><img alt="" src="/v/vspfiles/assets/images/alliance_small.jpg" align="right" />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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With