Lucas
Lucas

Reputation: 3715

Parse XML to get node value

I want to parse XML string like this one:

<Folk id="4630" country="US" name="Marry" />

(which is placed in the rich textbox editor)

And fetch the id, country, name values.

What have I tried:

 Dim content As String = Me.RichTextBox1.Text
 Dim doc As New System.Xml.XmlDocument

 Try
      doc.LoadXml(content)
 Catch ex As Exception
      Label2.Text = "No XML Elements!!!!"
 End Try

 Dim items = doc.GetElementsByTagName("Folk")

 For Each item As System.Xml.XmlElement In items
     Dim id As String = item.ChildNodes(0).InnerText()
     MsgBox(id) 'Try to prompt a message box containing the id=""
 Next

It does ends up with an error showing up: NullReferenceException was unhandled. - it doesnt found the id there, so I dont handle this error, first I would like to get the proper return, then I will handle if there is nothing found. So why it doesnt return the Folk id="" ? Is the access to the node called wrong?

Upvotes: 2

Views: 7819

Answers (1)

David Tansey
David Tansey

Reputation: 6023

The problem is the way that you are trying to reference the XML after it has been parsed.

Try changing this line:

Dim id As String = item.ChildNodes(0).InnerText()

To the following:

Dim id As String = item.Attributes(0)

country and name would be:

Dim country As String = item.Attributes(1)
Dim name As String = item.Attributes(2)

edit: sorry, I was speaking c# and vb.net at the same time. now fixed.

Upvotes: 1

Related Questions