Alejandro A Alejandro A - 6 months ago 13
Vb.net Question

Keep running code even if a nullException is found

I'm running a code where I'm reading an XML file and saving it in local variables using vb.net.

Sadly, not all of the XML are equally structure so I'm comming into the problem that if one field of those that I'm trying to map is missing it will stop running the code and prompt the error.

I would like, if a field is not fund, keep it as null and runs the code until the end.

I tried using try and catch with no luck.

Var1 = xmlNode.SelectSingleNode("Test1").InnerText
Var2 = xmlNode.SelectSingleNode("Test2").Value
Var3 = xmlNode.SelectSingleNode("Test3").InnerText


Now, if Var2 is missing on one of the xml's it will stop running the code and not take the Var3 even if present.

Thank you

Answer

If you are using Visual Studio 2015 you can use the null propagating operator ?

Var1 = xmlNode?.SelectSingleNode("Test1")?.InnerText
Var2 = xmlNode?.SelectSingleNode("Test2")?.Value
Var3 = xmlNode?.SelectSingleNode("Test3")?.InnerText

If you are using something older then you will have to do this long hand:

If xmlNode IsNot Nothing Then 
    Dim node = xmlNode.SelectSingleNode("Test1")
    If node IsNot Nothing then Var1 = node.InnerText
    node = xmlNode.SelectSingleNode("Test2")
    If node IsNot Nothing then Var1 = node.Value
    'etc.
End If

Note that you can do this using a Try...Catch but this would be ugly code:

Try
    Var1 = xmlNode.SelectSingleNode("Test1").InnerText
Catch ex As Exception
     'ignore
End Try
Try
    Var2 = xmlNode.SelectSingleNode("Test2").Value
Catch ex As Exception
     'ignore
End Try
Try
    Var3 = xmlNode.SelectSingleNode("Test3").InnerText
Catch ex As Exception
     'ignore
End Try

So if you have a lot of these you would be better wrapping this in a function:

Public Shared Function GetNodeInnerText(node as XmlNode, nodeName As String) As String
    If node Is Nothing Then Return ""
    Dim singleNode = node.SelectSingleValue(nodeName)
    If singleNode Is Nothing Then Return ""
    Return singleNode.InnerText
End Function