我有一个xml蚂蚁我试图chcke如果一个元素存在,如果是,那么如果它有一个值
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
这是一种好方法还是更好/更快?
由于
答案 0 :(得分:5)
尝试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