Var xmlList As XMLNodeList
Var xmlWalk As XMLDocument
Var sValue As string
...
xmlList = xmlWalk.XQL( "//product/sku" )
sValue = xmlList.item( 0 ).FirstChild.Value
Sometimes a product has a SKU and sometimes it does not.
I have tried:
Try
xmlList = xmlWalk.XQL( "//product/sku" )
sValue = xmlList.item( 0 ).FirstChild.Value
Catch e As XMLException
End Try
During debug I use the #Pragma BreakOnExceptions Off/On before and after the Try.
Is this the best way to be trapping or handling this kind of thing?
Once I go to compile the program I will remove the Pragma statements.
My thought: Your XQL/XPath selects all products with a sku-element and put them in the xmlList . products without sku-element are not getting added to this list. So i’m not sure where a Nil value should come from.
You need to iterate the items and check that they and their children aren’t nil before trying to use them.
What makes the code above problematic is that it assumes there’s an item 0, the value isn’t nil, there are children, there is a a first child, and the first child has a value. That is A LOT to assume in one line.
Without knowing what your XML document looks like, this is a guess based on what I think you might be looking for that illustrates how to iterate the nodes safely.
var xmlWalk as XMLDocument
var xmlList as XMLNodeList = xmlWalk.XQL("//product/sku")
// Iterate the children to find all SKU values
var iMax as Integer = xmlList.Length - 1
for i as Integer = 0 to iMax
var xnThis as XMLNode = xmlList.Item(i)
// Shouldn't happen, but without testing it's safer to have this in.
if xnThis = nil then continue for i
// No children to examine
if xnThis.ChildCount < 1 then continue for i
// There is a child so we can get the value
var sSku as String = xnThis.FirstChild.Value
// Do something with sSku to retain it, the loop will continue looking for skus
next i