Checking for Nil value in XQL

Hi All,

How do I check for a Nil value when using XQL?

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.

Thanks.

could u use .Length before reading FirstChild?

or

item = xmlList.item(0).FirstChild
sValue = ""
if item <> nil then sValue = item.Value

BreakOnExceptions
Once I go to compile the program I will remove the Pragma statements.

its basically that the ide do not interrupt and there is allways an error you know and managed by try catch.

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.

1 Like

I would expect that sometimes there is no mlList.item( 0 ) - if it finds no rows at all?
Or mlList.item( 0 ) has no children ? (Check the .childcount)

if it does, the .value property is a string, and wouldn’t itself be nil

1 Like

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