2016-05-16 64 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