簡體   English   中英

VB.net xml檢查元素是否存在以及是否具有值

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

我有一個xml ant,我嘗試檢查是否存在某個元素,如果是,那么它是否具有值
xml范例:

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

所以我想檢查OpenAtStart是否存在,然后再檢查它是否有一個值:所以我在下面建立了函數

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

這是一個好方法還是更好/更快?

謝謝

嘗試使用LINQ-XML有效地解析XML文檔/字符串。

 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM