Question Lopping XML into Listview

graham23s

Member
Joined
Feb 22, 2009
Messages
13
Programming Experience
1-3
Hi Guys,

i have my xml like:

PHP:
<?xml version="1.0" encoding="utf-8" ?>
<cities>
    <city>
        <name>Aberdeen</name>
        <code>UK</code>
    </city>
    <city>
        <name>Belfast</name>
        <code>UK</code>
    </city>
</cities>

code:

PHP:
                '// Create an instance of the XML 
                Dim XMLItem As New Xml.XmlDocument

                '// Find and load the XML file
                XMLItem.Load("Cities/cities.xml")

                Dim nodeList As XmlNodeList

                nodeList = XMLItem.DocumentElement.SelectNodes("/cities/city/name")

                Dim name As XmlNode

                For Each name In nodeList
                    'MessageBox.Show(name.InnerText)
                    With listViewCities.Items.Add(name.InnerText)
                        .SubItems.Add("code")
                    End With
                Next

I am trying to loop through the xml grabbing the values, then putting them in a listview, i can do the first part "name" but i'm not sure how to add in the "code" to the next column of the list view.

any help would be appreciated

thanks guys

Graham
 
VB.NET:
'// Create an instance of the XML
        Dim XMLDoc As New Xml.XmlDocument
        '// Find and load the XML file
        XMLDoc.Load("Cities/cities.xml")
        For Each node As Xml.XmlNode In XMLDoc.SelectNodes("cities/city")
            Dim lvItem As ListViewItem = listViewCities.Items.Add(node.Item("name").InnerText)
            lvItem.SubItems.Add(node.Item("code").InnerText)
        Next
 
Hi Mate,

Thank you for the help :)

i have implemented the code:

PHP:
                '// Create an instance of the XML 
                Dim XMLItem As New Xml.XmlDocument

                '// Find and load the XML file 
                XMLItem.Load("Cities/cities.xml")

                Dim nodeList As XmlNodeList

                For Each node As XmlNode In XMLItem.DocumentElement.SelectNodes("/cities/city")

                    Dim lvItem As ListViewItem = listViewCities.Items.Add(node.Item("name").InnerText)

                    Dim name As XmlNode

                    For Each name In nodeList

                        MessageBox.Show(name.InnerText)
                        With listViewCities.Items.Add(name.InnerText)
                            .SubItems.Add("code")
                        End With

                    Next

                Next

i get a message box saying "object reference not set to an instance of an object"

thanks mate

Graham
 
Means you should totally replace your existing code with this one:

VB.NET:
Dim XMLDoc As New Xml.XmlDocument
XMLDoc.Load("Cities/cities.xml")
For Each node As Xml.XmlNode In XMLDoc.SelectNodes("cities/city")
  Dim lvItem As ListViewItem = listViewCities.Items.Add(node.Item("name").InnerText)
  lvItem.SubItems.Add(node.Item("code").InnerText)
Next
 
Back
Top