Proper Handling When XMLNode.Value is Nil

Sometimes nodes in an XML file come in like this:

<trans></trans>

When parsing…

[code]dim n as XMLNode
dim value as String

while…

if n.name.trim = “trans” then
value = n.firstchild.Value.trim // Nil Object Exception here
end if

wend
[/code]
Is there a more elegant way to checking if each value is nil other than:

if n.name.trim = "trans" then if n.firstchild.Value <> Nil then value = n.firstchild.Value.trim end if end if

I have a lot of different nodes to check.
Thank you

I find the XML classes clumsy to use (your situation is a good example) so I always create an XMLExtensions module and put in those easier-to-use features.

something like this for getting text inside a node.

[code]Function innerText(extends node As XmlNode) As String
if node <> nil then
dim tn As XmlNode = node.FirstChild
if tn <> nil and tn IsA XmlTextNode then
return tn.Value
end
end
return “”
End Function

if n.Name.Trim = “trans” then
value = n.innerText.Trim
end[/code]

A whole set of these really helps to make XML useable, like getting first child with a name or attribute or all innerText with optional delimiter or xql results as an array, etc…

Shouldn’t you be checking ChildCount before you try to access a child?

Exactly. In fact, the code

if n.name.trim = "trans" then if n.firstchild.Value <> Nil then value = n.firstchild.Value.trim end if end if
would still throw a NilObjectException. Strings can’t be nil (there may be some really bizarre exceptions), but in this case, n.firstChild is nil.

Thanks guys. So in that case, then this should be sufficient, right?

[code]Function innerText(extends n As XmlNode) As String
// A node’s child count will be 0 when a tag is empty, i.e or

if n.ChildCount > 0 then
return n.FirstChild.Value.Trim
else
return “”
end if

End Function
[/code]