VB.net xml check element exist and if it has a value

Nianios picture Nianios · Jul 23, 2012 · Viewed 24.2k times · Source

I have an xml ant I am trying to chcke if an element exist and if yes then if it has a value
xml example:

<Attributes Version="1.0.2012">  
   <OpenAtStart>True</OpenAtStart>  
   <RefreshTime>60</RefreshTime>  
 </Attributes>  

So I want to check if OpenAtStart exists and then I want to check if it has a value : So I built the function , below

Private Function existsOrEmpty(ByVal type As Type, ByVal node As XmlNode, ByVal defaultValue As Object) As Object
    Dim myObj As Object = Nothing
    Try
        Cursor.Current = Cursors.WaitCursor
        If node IsNot Nothing Then
            Select Case type
                Case GetType(Integer)
                    If Integer.TryParse(node.InnerText, myObj) = False Then
                        myObj = defaultValue
                    End If
                Case GetType(Double)
                    If Double.TryParse(node.InnerText, myObj) = False Then
                        myObj = defaultValue
                    End If
                Case GetType(Boolean)
                    If Boolean.TryParse(node.InnerText, myObj) = False Then
                        myObj = defaultValue
                    End If
                Case Else
                    myObj = node.InnerText
            End Select
        Else
            myObj = defaultValue
        End If

    Catch ex As Exception
        gError.GetAppEx(ex, CLASS_NAME & ".existsOrEmpty")
    Finally
        Cursor.Current = Cursors.Default
    End Try
    Return myObj
End Function

Is this a good way or there is a better/faster ?

Thanks

Answer

kv-prajapati picture kv-prajapati · Jul 23, 2012

Try LINQ-XML to parse XML document/string effectively.

 Dim str = "<Attributes Version=""1.0.2012"">" _
                   & "<OpenAtStart>True</OpenAtStart>" _
                   & "<RefreshTime>60</RefreshTime></Attributes>"

 Dim doc As XDocument = XDocument.Parse(str)
 Dim element = doc.Root.Element("OpenAtStart")

 If IsNothing(element) Then
      Console.WriteLine("Not Found")
 Else
      Console.WriteLine(element.Value)
      Console.WriteLine(element.Parent.Element("RefreshTime").Value)
 End If