We help IT Professionals succeed at work.

How do I read XML Nodes in VB.NET?

595 Views
Last Modified: 2013-11-19
Hi All,

I want to read XML Nodes value in my application and set it's value in a datagrid. I am able to find starting node but am not able to extract values of other elements.

For e.g:
<rss version='2.0' xmlns:channel='download.com/rss/newMac'>
<channel>
  <title>CNET Download.com 25 Newest Mac Titles</title>
  <description>New Mac software downloads from CNET Download.com.</description>
  <copyright>Copyright 1997-2003 CNET Networks, Inc.</copyright>
  <link>http://download.com.com/2001-2003-0.html?tag=dir</link>
  <language>en-us</language>
  <lastBuildDate>Mon, 16 Feb 2004 03:00:01 -0800</lastBuildDate>
  <ttl>24</ttl>
      
<item>
  <title>iPod Access 3.1.1</title>
  <link>http://download.com.com/3000-2199-10263210.html?tag=WinTracking</link>
  <description>Transfer song titles from your iPod to Mac.</description>
  <pubDate>Fri, 13 Feb 2004 00:00:00 -0800</pubDate>
</item>
</channel>
</rss>

In the above XML code my code determines <channel> as starting node but i am not able to extract values of title, description, copyright etc.. I also need to loop through <item> nodes. Any help is highly appreciated.
Comment
Watch Question

DCD

Commented:

        Dim reader As XmlTextReader = New XmlTextReader("C:\rss.xml")
        Do While (reader.Read())
            Select Case reader.NodeType
                Case XmlNodeType.Element 'Display beginning of element.
                    Select Case reader.Name
                        Case "Channel"
                            Dim details as string
                            details = reader.ReadElementString.ToString
                        Case "item"
                            Dim title as string
                            reader.MoveToFirstAttribute() 'This would bring you to the Title attribute
                            title = reader.Value 'This would get the title informat
                    End Select
                    If reader.HasAttributes Then 'If attributes exist
                        While reader.MoveToNextAttribute() 'Display attribute name and value.
                            Select Case reader.Name
                                Case "link"
                                    Dim myLink as string
                                    myLink = reader.Value
                                Case "description"
                                    Dim myDescription as string
                                    myDescription = reader.Value
                                Case ""

                            End Select
                        End While
                    End If
            End Select
        Loop

If you look at the two select statements you will get the idea at how to get the attributes, etc.

DCD

Commented:
Here is a solution:
Open a new windows application and add a new form.
Copy the following code:

Imports System.Xml

Public Class XMLExample
    Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call

    End Sub

    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    Friend WithEvents btnLoadXml As System.Windows.Forms.Button
    Friend WithEvents lbNodes As System.Windows.Forms.ListBox
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.btnLoadXml = New System.Windows.Forms.Button
        Me.lbNodes = New System.Windows.Forms.ListBox
        Me.SuspendLayout()
        '
        'btnLoadXml
        '
        Me.btnLoadXml.Location = New System.Drawing.Point(8, 8)
        Me.btnLoadXml.Name = "btnLoadXml"
        Me.btnLoadXml.Size = New System.Drawing.Size(112, 23)
        Me.btnLoadXml.TabIndex = 0
        Me.btnLoadXml.Text = "Load XML"
        '
        'lbNodes
        '
        Me.lbNodes.Location = New System.Drawing.Point(8, 48)
        Me.lbNodes.Name = "lbNodes"
        Me.lbNodes.Size = New System.Drawing.Size(432, 355)
        Me.lbNodes.TabIndex = 1
        '
        'StepByStep6_28
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(456, 413)
        Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.lbNodes, Me.btnLoadXml})
        Me.Name = "StepByStep6_28"
        Me.Text = "StepByStep6_28"
        Me.ResumeLayout(False)

    End Sub

#End Region

    Private Sub btnLoadXml_Click(ByVal sender As System.Object, _
     ByVal e As System.EventArgs) Handles btnLoadXml.Click
        ' Browse for an XML file
        Dim dlgOpen As New OpenFileDialog
        dlgOpen.Title = "Select a File"
        dlgOpen.Filter = "XML files (*.xml)|*.xml|All Files(*.*)|*.*"
        If dlgOpen.ShowDialog = DialogResult.OK Then
            ' Hook up to the disk file
            Dim xtr As New XmlTextReader(dlgOpen.FileName)
            xtr.WhitespaceHandling = WhitespaceHandling.None
            Dim xd As XmlDocument = New XmlDocument
            ' Load the file into the XmlDocument
            xd.Load(xtr)
            ' Add an item representing the document to the ListBox
            lbNodes.Items.Add("XML Document")
            ' Find the root node, and add it together with its children
            Dim xnod As XmlNode = xd.DocumentElement
            AddWithChildren(xnod, 1)
        End If
    End Sub

    Private Sub AddWithChildren(ByVal xnod As XmlNode, ByVal intLevel As Integer)
        ' Adds a node to the ListBox, together with its children.
        ' intLevel controls the depth of indenting
        Dim xnodWorking As XmlNode
        Dim tnodWorking As TreeNode
        Dim tnodAttribute As TreeNode

        Dim strIndent As String = New String(" ", 2 * intLevel)
        ' Get the value of the node (if any)
        Dim strValue As String = CType(xnod.Value, String)
        If Len(strValue) > 0 Then
            strValue = " : " & strValue
        End If
        ' Add the node details to the ListBox
        lbNodes.Items.Add(strIndent & xnod.Name & strValue)
        ' For an element node, retrieve the attributes
        If xnod.NodeType = XmlNodeType.Element Then
            Dim mapAttributes As XmlNamedNodeMap = xnod.Attributes
            Dim xnodAttribute As XmlNode
            ' Add the attrbutes to the ListBox
            For Each xnodAttribute In mapAttributes
                lbNodes.Items.Add(strIndent & "  " & xnodAttribute.Name & " : " & xnodAttribute.Value)
            Next
        End If
        ' If there are any child nodes, call this procedure recursively
        If xnod.HasChildNodes Then
            xnodWorking = xnod.FirstChild
            Do Until IsNothing(xnodWorking)
                AddWithChildren(xnodWorking, intLevel + 1)
                xnodWorking = xnodWorking.NextSibling
            Loop
        End If
    End Sub

End Class

Commented:
Copy this one:

Imports System.Xml

Public Class XMLExample
    Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call

    End Sub

    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    Friend WithEvents btnLoadXml As System.Windows.Forms.Button
    Friend WithEvents lbNodes As System.Windows.Forms.ListBox
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.btnLoadXml = New System.Windows.Forms.Button
        Me.lbNodes = New System.Windows.Forms.ListBox
        Me.SuspendLayout()
        '
        'btnLoadXml
        '
        Me.btnLoadXml.Location = New System.Drawing.Point(8, 8)
        Me.btnLoadXml.Name = "btnLoadXml"
        Me.btnLoadXml.Size = New System.Drawing.Size(112, 23)
        Me.btnLoadXml.TabIndex = 0
        Me.btnLoadXml.Text = "Load XML"
        '
        'lbNodes
        '
        Me.lbNodes.Location = New System.Drawing.Point(8, 48)
        Me.lbNodes.Name = "lbNodes"
        Me.lbNodes.Size = New System.Drawing.Size(432, 355)
        Me.lbNodes.TabIndex = 1
        '
        'XMLExample
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(456, 413)
        Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.lbNodes, Me.btnLoadXml})
        Me.Name = "XMLExample"
        Me.Text = "XMLExample"
        Me.ResumeLayout(False)

    End Sub

#End Region

    Private Sub btnLoadXml_Click(ByVal sender As System.Object, _
     ByVal e As System.EventArgs) Handles btnLoadXml.Click
        ' Browse for an XML file
        Dim dlgOpen As New OpenFileDialog
        dlgOpen.Title = "Select a File"
        dlgOpen.Filter = "XML files (*.xml)|*.xml|All Files(*.*)|*.*"
        If dlgOpen.ShowDialog = DialogResult.OK Then
            ' Hook up to the disk file
            Dim xtr As New XmlTextReader(dlgOpen.FileName)
            xtr.WhitespaceHandling = WhitespaceHandling.None
            Dim xd As XmlDocument = New XmlDocument
            ' Load the file into the XmlDocument
            xd.Load(xtr)
            ' Add an item representing the document to the ListBox
            lbNodes.Items.Add("XML Document")
            ' Find the root node, and add it together with its children
            Dim xnod As XmlNode = xd.DocumentElement
            AddWithChildren(xnod, 1)
        End If
    End Sub

    Private Sub AddWithChildren(ByVal xnod As XmlNode, ByVal intLevel As Integer)
        ' Adds a node to the ListBox, together with its children.
        ' intLevel controls the depth of indenting
        Dim xnodWorking As XmlNode
        Dim tnodWorking As TreeNode
        Dim tnodAttribute As TreeNode

        Dim strIndent As String = New String(" ", 2 * intLevel)
        ' Get the value of the node (if any)
        Dim strValue As String = CType(xnod.Value, String)
        If Len(strValue) > 0 Then
            strValue = " : " & strValue
        End If
        ' Add the node details to the ListBox
        lbNodes.Items.Add(strIndent & xnod.Name & strValue)
        ' For an element node, retrieve the attributes
        If xnod.NodeType = XmlNodeType.Element Then
            Dim mapAttributes As XmlNamedNodeMap = xnod.Attributes
            Dim xnodAttribute As XmlNode
            ' Add the attrbutes to the ListBox
            For Each xnodAttribute In mapAttributes
                lbNodes.Items.Add(strIndent & "  " & xnodAttribute.Name & " : " & xnodAttribute.Value)
            Next
        End If
        ' If there are any child nodes, call this procedure recursively
        If xnod.HasChildNodes Then
            xnodWorking = xnod.FirstChild
            Do Until IsNothing(xnodWorking)
                AddWithChildren(xnodWorking, intLevel + 1)
                xnodWorking = xnodWorking.NextSibling
            Loop
        End If
    End Sub

End Class

Author

Commented:
@ DCD

The code isn't working as expected. I am not able to retrieve any values. Your code attempts to get values of a Element's attributes and not of element itself.

E.g:
The code will return true for this element as it has xmlns:channel & version as it's attributes:
<rss version='2.0' xmlns:channel='download.com/rss/newMac'>

False in these two situations:
<channel>
<title>CNET Download.com 25 Newest Mac Titles</title>

I need to demarcate Channel's and Item's elements seperately. Please let me know if you have the solution to this.

Thanks.

@ LiorRon

Can you pls post a more simpler code...just the XML part?

Thanks.
DCD

Commented:
digitalone: I have something important to take care of, but I will give you an example of what will work with your rss feed soon.

DCD
DCD

Commented:
digitalone: I can provide, but you can adjust the code to just read the elements. In the above example here are the elements:

>CHANNEL
title
description
copyright
link
language
lastbuilddate
ttl

>ITEM
title
link
description
pubdate

Dim reader As XmlTextReader = New XmlTextReader("C:\rss.xml")
        Do While (reader.Read())
            Select Case reader.NodeType
                Case XmlNodeType.Element 'Display beginning of element.
                    Select Case reader.Name
                        Case "title"
                            Dim details as string
                            details = reader.ReadElementString.ToString
                        Case "description"
                            Dim title as string
                            title = reader.ReadElementString.ToString
                    End Select
                    End while
            End Select
        Loop

DCD
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.