Reputation: 2645
I have a pretty generic xml file which I'm looking to parse, however, I'm not too sure where to find such a tutorial to read data from xml files. I'm looking to create a card game, and I'm looking to be able to create my own cards. I've already created the file that creates the cards but now I have to read them.
This is the format of my xml file:
<?xml version="1.0" encoding="utf-8"?>
<Cards>
<Card>
<ID>1</ID>
<Name>Cardsname</Name>
<Type>teetete</Type>
<Image>1gc.jpg</Image>
<Description>test</Description>
</Card>
</Cards>
As you can see, theres a root node called 'Cards' which contains all of the cards. I need to access this node and find all of the 'Card' nodes and their children (id, name, type, image). How would I access the text within these?
EDIT: Just figured out how to access it but can't figure out how to loop it. If i wanted to access multiple elements, how would I do so?
Sub Main()
Dim output As StringBuilder = New StringBuilder()
Using reader As XmlReader = New XmlTextReader("C:\Godlycards\cards.xml")
reader.ReadToFollowing("Card")
reader.MoveToFirstAttribute()
reader.ReadToFollowing("ID")
output.AppendLine("ID: " + reader.ReadElementContentAsString())
reader.ReadToFollowing("Name")
output.AppendLine("Name: " + reader.ReadElementContentAsString())
reader.ReadToFollowing("Type")
output.AppendLine("Type: " + reader.ReadElementContentAsString())
reader.ReadToFollowing("Image")
output.AppendLine("Image: " + reader.ReadElementContentAsString())
reader.ReadToFollowing("Description")
output.AppendLine("Description: " + reader.ReadElementContentAsString())
MessageBox.Show(output.ToString)
End Using
End Sub
Thanks!
Upvotes: 1
Views: 258
Reputation: 26414
XDocument / XElement is a convenient way of handling things in your case. Consider this example:
Dim xml As XDocument = <?xml version="1.0" encoding="utf-8"?>
<Cards>
<Card>
<ID>1</ID>
<Name>Cardsname</Name>
<Type>teetete</Type>
<Image>1gc.jpg</Image>
<Description>test</Description>
</Card>
</Cards>
Yes, you can paste raw xml into your code like this.
Then your collection of cards can be accessed using this approach:
Dim cards As IEnumerable(Of XElement) = xml.Root.Elements("Card")
For a particular card, you get its properties like this:
Dim cardID As String = cards(0).Element("ID").Value
As a side note, you would probably be using XDocument.Load
or XDocument.Parse
, instead of having your XML inline with your code. Rest is the same.
Upvotes: 1