Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

xml

vbscript

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.

like image 470
user357034 Avatar asked Oct 10 '11 14:10

user357034


2 Answers

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
like image 128
Jon Egerton Avatar answered Oct 12 '22 23:10

Jon Egerton


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
like image 23
Paul Graffam Avatar answered Oct 12 '22 21:10

Paul Graffam