Reputation: 409
I am writing a Sub that reads an XML file from a given path, and then loads it into an array of objects. For some reason, the algorithm works fine for the name, but refuses to work with the cost and type tags. What is going on?
(UPDATE: refuses to work means it returns an empty string, or in the case of cost: 0)
Here is my code:
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
Here is the XML file: Mona Lisa 2000 art Polka Dots 35.85 art
Upvotes: 0
Views: 42
Reputation: 6969
Reading XML data the way you are doing is both clumsy as well as error-prone. It is much better to use XPath Expressions
to extract the data of your interest from an XML file, which gets you the data in just one line of code.
You can learn more about XPath Expressions
syntax here, to get yourself started:
http://www.w3schools.com/xsl/xpath_syntax.asp
To learn how to use Xpath expressions in VB.NET code, you may find a lot of interesting articles on the internet. One of them that explains it in an easy to understand language is here:
Upvotes: 1