我有一個XML格式的文檔,看起來像這樣:XML在vb.net解析
<?xml version="1.0" encoding="windows-1250"?>
< Recipe>
< Entry name="Stuffed Red Cabbage" ethnicity="Slavic" />
< Cook_Time Hrs="1" Mins="30" />
< Ingredients>
< Cabbage Amount="1" Measurement="head" />
< Egg Amount="1" Measurement="unit" />
< Ground_Beef Amount="1" Measurement="lb" />
< Margarine Amount="1/2" Measurement="cup" />
< Onion Amount="1" Measurement="unit" />
< Rice Amount="1" Measurement="cup" />
< Tomato_Soup Amount="3" Measurement="cans" />
< /Ingredients>
< Description>core cabbage and boil until leaves start pulling away. Strip leaves and let cool.
chop onion and place in frying pan with margarine and heat till lightly browned.
put ground beef, rice, onion, egg and salt to taste in bowl and mix.
stuff each leaf with mixture.
put tomato soup and stuffed leaves in pot and cook for about an hour.</Description>
</Recipe>
,我有代碼,到目前爲止是這樣的:
OpenFileDialog1.Filter = "RecipeBook files (*.rcp)|*.rcp"
If OpenFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
Dim settings As New XmlReaderSettings()
settings.IgnoreComments = True
Dim RecipeCard As String = OpenFileDialog1.FileName
Dim xmlreader As XmlTextReader
xmlreader = New XmlTextReader(RecipeCard)
Do While xmlreader.Read
'needs to read xml and write appropriate items to database and listview
xmlreader.MoveToContent()
If xmlreader.Name.Equals("Entry") Then
MessageBox.Show(xmlreader.GetAttribute("name") & " " & xmlreader.GetAttribute("ethnicity"), "test")
End If
If xmlreader.Name.Equals("Cook_Time") Then
MessageBox.Show(xmlreader.GetAttribute("Hrs") & " hrs " & xmlreader.GetAttribute("Mins") & " mins", "test")
End If
If xmlreader.Name.Equals("Ingredients") Then
End If
Loop
Catch
End Try
End If
我的問題必須做解析配料部分。我打算做這樣的事情:
Dim IngredientCount As Integer = 0
Dim count As Integer = (something here that gets the count of subelements inside the Ingredients element)
For i = 1 To count
MessageBox.Show(xmlreader.GetAttribute("Amount") & " " & xmlreader.GetAttribute("Measurement"), "test")
Next
我只是無法弄清楚如何讓子元素的數量,再怎麼是指每一個連續獲得的名稱,然後那屬性子元素。任何建議將不勝感激。
您使用.net 3.5嗎? Xlinq將使這更容易。 http://msdn.microsoft.com/en-us/vbasic/bb738050.aspx – 2009-12-12 19:58:29
我使用3.5,我需要重用3.5緊湊,以及我會看看。 – MaQleod 2009-12-12 20:02:59