我正在编写一个从给定路径读取XML文件的Sub,然后将其加载到对象数组中。出于某种原因,该算法适用于名称,但拒绝使用成本和类型标记。发生了什么事?
(更新: 拒绝工作表示它返回一个空字符串,或者在成本为0的情况下)
这是我的代码:
Public Sub New(ByVal Path As String)
Try
Dim XML As New XmlTextReader(Path)
Try
Dim Bool As Boolean = False
Dim Name As String = ""
Dim Cost As Double = 0
Dim Type As String = ""
While True
XML.Read()
If Bool Then
Select Case XML.Name
Case Is = "name"
XML.Read()
Name = XML.Value
Case Is = "cost"
XML.Read()
Double.TryParse(XML.Value, Cost)
Case Is = "type"
XML.Read()
Type = XML.Value
End Select
End If
If XML.Name = "card" Then
Bool = True
End If
If Not CheckNulls(Name, Cost, Type) Then //CheckNulls returns true if all arguments passed to it are either empty strings, or 0
Dim Card As New Card(Name, Cost, Type)
Deck.Add(Card)
Cost = 0
Name = ""
Type = ""
Bool = False
End If
End While
Catch Ex As Exception
Exit Sub
End Try
Catch Ex As Exception
MsgBox("The System has encountered an error. Running the software anymore could cause a serious malfunction. Please exit now", MsgBoxStyle.OkOnly, "Error Message")
End Try
End Sub
这是XML文件: 蒙娜丽莎 2000 艺术 波尔卡圆点 35.85 艺术
答案 0 :(得分:1)
以您的方式阅读XML数据既笨拙又容易出错。最好使用XPath Expressions
从XML文件中提取您感兴趣的数据,只需一行代码即可获取数据。
您可以在此处详细了解XPath Expressions
语法,以便开始使用
http://www.w3schools.com/xsl/xpath_syntax.asp
要了解如何在VB.NET代码中使用Xpath表达式,您可能会在互联网上找到很多有趣的文章。其中一个以易于理解的语言解释它是: