VB.net xml 检查元素是否存在以及它是否具有值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11609655/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VB.net xml check element exist and if it has a value
提问by Nianios
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:
我有一个 xml ant 我正在尝试检查元素是否存在,如果是,则它是否具有值
xml 示例:
<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
所以我想检查 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
Is this a good way or there is a better/faster ?
这是一个好方法还是有更好/更快的方法?
Thanks
谢谢
回答by adatapost
Try LINQ-XMLto parse XML document/string effectively.
尝试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

