Promote Your Blog

Saturday, January 14, 2012

How To Parse XML File For Particular Node and Children Information

Suppose you want to parse XML file generated in my blog post, How To Generate XML File Using Visual Basic, and retrieve information about a particular book and display it in various controls of GUI.

The code for same is given below:

Imports System.Xml
Imports System.IO

Dim doc As New XmlDocument
Dim cnt As Integer
For Each node As XmlNode In doc.GetElementsByTagName("BOOK")

'if book node is same for which you want information
If node.ChildNodes(0).InnerText = cmbBook.Text Then
lblISBN.Text = node.ChildNodes(1).InnerText
lblAuthor.Text = node.ChildNodes(2).InnerText

dgvChapter.Rows.Clear() 'to display chapter information
'Get child nodes of BOOK node
Dim nc As Integer = node.ChildNodes.Count

'Fill chapters information in DataGridView control
For cnt = 3 To nc - 1
dgvPHC.Rows.Add(node.ChildNodes(cnt).ChildNodes(0).InnerText, node.ChildNodes(cnt).ChildNodes(1).InnerText, node.ChildNodes(cnt).ChildNodes(2).InnerText)
Next cnt

End If


Catch errorVariable As Exception
End Try

No comments:

Post a Comment