2016-05-16 63 views
0

我正在寫一個從給定路徑讀取XML文件,然後將其加載到對象數組中的子。出於某種原因,該算法對名稱工作正常,但拒絕使用成本和類型標籤。到底是怎麼回事?XML閱讀子不工作

UPDATE:拒絕工作意味着它返回一個空字符串,或在成本的情況下: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文件: 蒙娜麗莎藝術 個圓點 35.85 藝術

+0

你是什麼意思與「拒絕工作」:不存在發生錯誤或者是它只是一個空字符串等?另外請提供您正在嘗試解析的XML文件。 – DAXaholic

+0

瞭解「XPath」表達式。你會更快樂。 http://www.w3schools.com/xsl/xpath_syntax.asp –

+0

@Pradeep Kumar如何在VB.NET中使用XPath? –

回答

1

讀取XML數據,你正在做的方式是既笨拙以及容易出錯。使用XPath Expressions從XML文件中提取感興趣的數據要好得多,它只需一行代碼即可獲取數據。

您可以瞭解更多關於XPath Expressions語法這裏,以讓自己開始:

http://www.w3schools.com/xsl/xpath_syntax.asp

要學習如何在VB.NET代碼使用XPath表達式,你會發現有很多的有趣的文章互聯網。其中之一,說明它在一個易於理解的語言是在這裏:

http://www.aspsnippets.com/Articles/XmlDocument-XPath-Example-Select-XML-nodes-by-Name-and-Attribute-values-in-C-and-VBNet.aspx