Results 1 to 15 of 15

Thread: XML in Listview

  1. #1

    Thread Starter
    Member
    Join Date
    Jun 2002
    Posts
    33

    XML in Listview

    I am brand new to XML and VB.NET and i was wondering how would i go about getting data out of an XML file and putting it into a ListView?

  2. #2
    Fanatic Member
    Join Date
    Sep 2002
    Posts
    518
    I think the simplest way (although you should ask around) is to first load the XML file into a dataset, and then have some code to stick the dataset's table data into a listview. Listview all by itself does not support reading XML data, but I fill ListViews from datasets all the time and it seems to work better than trying to teach ListView how to understand XML.

    For info on datasets and how to read XML files into them:
    ms-help://MS.VSCC/MS.MSDNVS/cpref/html/frlrfSystemDataDataSetClassTopic.htm
    ms-help://MS.VSCC/MS.MSDNVS/cpguide/html/cpconloadingdatasetfromxml.htm

    Note that if you aren't using a schema file, the DataSet.ReadXML method can infer the schema from the data if it isn't too complicated:
    ms-help://MS.VSCC/MS.MSDNVS/cpguide/html/cpconinferringdatasetrelationalstructurefromxml.htm

    Once you have your data loaded into the dataset, you can examine a table and create ListViewItems for each record like so:

    Code:
            Dim lvwColumn As ColumnHeader
            Dim itmListItem As ListViewItem
            Dim shtCntr As Short
            Dim objRow As DataRow
            'Empty the listview
            lvwItems.Clear()
            'Suspend redrawing until we are done adding items
            lvwItems.BeginUpdate()
            'populate the listview columns
            Try
                For shtCntr = 0 To dsDataSet.Tables("TableName").Columns.Count - 1
                    lvwColumn = New ColumnHeader()
                    'Create Column Header
                    lvwColumn.Text = dsDataSet.Tables("TableName").Columns.Item(shtCntr).ColumnName.ToString
                    lvwItems.Columns.Add(lvwColumn)
                Next
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try
    
            'Populate the listview items
            For Each objRow In dsDataSet.Tables("TableName").Select("SomeField = 'SomeValue'")
                itmListItem = New ListViewItem()
                itmListItem.Text = objRow.ItemArray(0)
                For shtCntr = 1 To objRow.ItemArray.GetUpperBound(0)
                    itmListItem.SubItems.Add(objRow.ItemArray.GetValue(shtCntr))
                Next
                lvwItems.Items.Add(itmListItem)
            Next
    
            lvwItems.EndUpdate()
    Last edited by Slow_Learner; Apr 23rd, 2003 at 11:30 PM.

  3. #3
    Lively Member
    Join Date
    Feb 2003
    Location
    UK
    Posts
    95
    .NET has a rich XML API that is more than adequate.

    You can load the XML file into an internal DOM using the XMLDocument class and using XPATH extract the required information and placing it in the listview.
    See my post on this thread for a great book on the subject.

  4. #4
    Fanatic Member
    Join Date
    Sep 2002
    Posts
    518
    See, there is more than one way to skin a cat

    Based on:
    ms-help://MS.VSCC/MS.MSDNVS/xmlsdk30/htm/xmconintroductiontothedom.htm

    ...it seems like it would end up being six of one, half dozen of the other. I dunno if either way would be shorter or consume less resources, although for small apps and small data I'm sure it doesn't matter much.

  5. #5

    Thread Starter
    Member
    Join Date
    Jun 2002
    Posts
    33
    How do i define the first two variables? I keep getting error
    Type ColumnHeader is not defined and Type ListViewItem is not defined.

  6. #6
    Fanatic Member
    Join Date
    Sep 2002
    Posts
    518
    An example of defining a dataset from code:
    Code:
        'up near the top, because we want this to be declared app-wide
        Private dsData As DataSet
    
       Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            InitDataSet()
        End Sub
    
        Private Sub InitDataSet()
            dsData = New DataSet()
    
            Dim myDataColumn As DataColumn
            Dim myDataRow As DataRow
            Dim iCount As Integer
    
            'Set up table
            Dim tbl As DataTable = New DataTable("Number")
            tbl.CaseSensitive = True
            myDataColumn = New DataColumn()
            myDataColumn.DataType = System.Type.GetType("System.Int32")
            myDataColumn.ColumnName = "Number"
            myDataColumn.Unique = False
            ' Add the Column to the DataColumnCollection.
            tbl.Columns.Add(myDataColumn)
    
            dsData.Tables.Add(tbl)
    
            'Add some records
            For iCount = 1 To 100
                myDataRow = dsData.Tables("Number").NewRow()
                myDataRow("Number") = iCount
                dsData.Tables("Number").Rows.Add(myDataRow)
            Next
        End Sub
    As to why you're getting the type not defined errors, you shouldn't be, System.Data is the namespace in which they reside and 'should' be imported by default for a Windows Forms. If the above code gives you the same error, try adding:

    Imports System.Data

    to the top of your class.

  7. #7

    Thread Starter
    Member
    Join Date
    Jun 2002
    Posts
    33
    I think i understand how to set up the dataset. How do i get the data into the listview?

  8. #8
    Fanatic Member
    Join Date
    Sep 2002
    Posts
    518
    Scroll up in this thread.

    Oh woops, you wanted to know how to get XML imported into something useful right? Sorry, I lost track. Look at DataSet.ReadXML:

    ms-help://MS.VSCC/MS.MSDNVS/cpref/html/frlrfSystemDataDataSetClassReadXmlTopic.htm
    Last edited by Slow_Learner; Apr 25th, 2003 at 11:57 PM.

  9. #9

    Thread Starter
    Member
    Join Date
    Jun 2002
    Posts
    33
    who could I get this in a listview

    Code:
    <?xml version="1.0" encoding="utf-8" ?>
    <FileList xmlns="http://tempuri.org/Config.xsd">
    	<File>
                               <Main>
    			<File_x0020_Name>Test.KXK</File_x0020_Name>
    			<File_x0020_Path>C:\TEST.KXK</File_x0020_Path>
    			<File_x0020_code>1</File_x0020_code>
    		</Main>
    	</File>
    </FileList>
    this is the code i am trying to use

    VB Code:
    1. Private Sub DemonstrateReadWriteXMLDocumentWithStreamReader()
    2.         ' Create a DataSet with one table and two columns.
    3.         Dim OriginalDataSet As New DataSet("ConFig")
    4.         OriginalDataSet.Namespace = "http://tempuri.org/Config.xsd"
    5.         Dim myTable As New DataTable("Pics")
    6.         Dim c1 As New DataColumn("Name", Type.GetType("System.Int32"))
    7.         c1.AutoIncrement = True
    8.         Dim c2 As New DataColumn("Path")
    9.         myTable.Columns.Add(c1)
    10.         myTable.Columns.Add(c2)
    11.         OriginalDataSet.Tables.Add(myTable)
    12.         ' Add ten rows.
    13.         Dim newRow As DataRow
    14.         Dim i As Integer
    15.         For i = 0 To 9
    16.             newRow = myTable.NewRow()
    17.             newRow("Path") = "Path" + i.ToString()
    18.             myTable.Rows.Add(newRow)
    19.         Next i
    20.         OriginalDataSet.AcceptChanges()
    21.         ' Print out values of each table in the DataSet using the
    22.         ' function defined below.
    23.         PrintValues(OriginalDataSet, "Original DataSet")
    24.         ' Write the schema and data to an XML file.
    25.         Dim xmlFilename As String = "C:\Documents and Settings\Kenny\My Documents\Visual Studio Projects\Pic Viewer XP\Config.xml"
    26.         ' Use WriteXml to write the document.
    27.         OriginalDataSet.WriteXml(xmlFilename)
    28.         ' Dispose of the original DataSet.
    29.         OriginalDataSet.Dispose()
    30.         ' Create a new DataSet.
    31.         Dim newDataSet As New DataSet("New DataSet")
    32.         ' Read the XML document into the DataSet.
    33.         newDataSet.ReadXml(xmlFilename)
    34.         ' Print out values of each table in the DataSet using the
    35.         ' function defined below.
    36.         PrintValues(newDataSet, "New DataSet")
    37.     End Sub
    38.  
    39.  
    40.     Private Sub PrintValues(ByVal ds As DataSet, ByVal label As String)
    41.         Console.WriteLine(ControlChars.Cr + label)
    42.         Dim t As DataTable
    43.         For Each t In ds.Tables
    44.             Console.WriteLine("TableName: " + t.TableName)
    45.             Dim r As DataRow
    46.             For Each r In t.Rows
    47.                 Dim c As DataColumn
    48.                 For Each c In t.Columns
    49.                     Console.Write(ControlChars.Tab + " " + r(c).ToString())
    50.                 Next c
    51.                 Console.WriteLine()
    52.             Next r
    53.         Next t
    54.     End Sub
    Last edited by kenya87; Apr 26th, 2003 at 12:52 AM.

  10. #10
    Fanatic Member
    Join Date
    Sep 2002
    Posts
    518
    Okay let's take a look.

    Code:
    'Up at the top of your class you would declare your DataSet
    'so it will be accessible application-wide
    Dim dsData As New DataSet("Files")
    
    Dim xmlFileName As String = "C:\Documents and Settings\Kenny\My Documents\Visual Studio Projects\Pic Viewer XP\Config.xml"
    
    
    'Read in the xml file and infer the dataset schema
    Private Sub ReadXMLFile()
        ' Read the XML document back in. 
        ' Create new FileStream to read schema with.
        Dim fsReadXml As New System.IO.FileStream _
           (xmlFilename, System.IO.FileMode.Open)
        ' Create an XmlTextReader to read the file.
        Dim myXmlReader As New System.Xml.XmlTextReader(fsReadXml)
        ' Read the XML document into the DataSet.
        newDataSet.ReadXml(myXmlReader)
        ' Close the XmlTextReader
        myXmlReader.Close   
    End Sub
    For me at least, this code takes your xml file given above and imports it into a DataSet, one of whose tables is called "Main". This table has one row, which follows the structure you show in your XML file. Now to stick that into a listview:
    Code:
       Private Sub FillListView()
            Dim lvwColumn As ColumnHeader
            Dim itmListItem As ListViewItem
            Dim shtCntr As Short
            Dim objRow As DataRow
            'Empty the listview
            lvwItems.Clear()
            'Suspend redrawing until we are done adding items
            lvwItems.BeginUpdate()
            'populate the listview columns
            Try
                For shtCntr = 0 To dsData.Tables("Main").Columns.Count - 1
                    lvwColumn = New ColumnHeader()
                    'Create Column Header
                    lvwColumn.Text = dsData.Tables("Main").Columns.Item(shtCntr).ColumnName.ToString
                    lvwItems.Columns.Add(lvwColumn)
                Next
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try
    
            'Populate the listview items
            'Since we have only one record, let's just select all
            'rather than specify a criteria
            For Each objRow In dsData.Tables("Main").Select()
                itmListItem = New ListViewItem()
                itmListItem.Text = objRow.ItemArray(0)
                For shtCntr = 1 To objRow.ItemArray.GetUpperBound(0)
                    itmListItem.SubItems.Add(objRow.ItemArray.GetValue(shtCntr))
                Next
                lvwItems.Items.Add(itmListItem)
            Next
    
            lvwItems.EndUpdate()
    
        End Sub
    Entire project attached.
    Attached Files Attached Files

  11. #11

    Thread Starter
    Member
    Join Date
    Jun 2002
    Posts
    33
    This code works great for one row but what if i want more than one row?

  12. #12
    Fanatic Member
    Join Date
    Sep 2002
    Posts
    518
    More rows in your XML should equate to more rows in your listview. Does it not work? Give a copy of your xml file and I'll try it, it should work for any number of rows.

  13. #13
    Fanatic Member
    Join Date
    Sep 2002
    Posts
    518
    Actually I dug up the project file for when we last talked about this and added some records to your original xml file as below:
    Code:
    <?xml version="1.0" encoding="utf-8" ?>
    <FileList xmlns="http://tempuri.org/Config.xsd">
     <File>
      <Main>
       <File_x0020_Name>Test.KXK</File_x0020_Name>
       <File_x0020_Path>C:\TEST.KXK</File_x0020_Path>
       <File_x0020_code>1</File_x0020_code>
      </Main>
      <Main>
       <File_x0020_Name>Test2.KXK</File_x0020_Name>
       <File_x0020_Path>C:\TEST2.KXK</File_x0020_Path>
       <File_x0020_code>1</File_x0020_code>
      </Main>
      <Main>
       <File_x0020_Name>Test3.KXK</File_x0020_Name>
       <File_x0020_Path>C:\TEST3.KXK</File_x0020_Path>
       <File_x0020_code>1</File_x0020_code>
      </Main>
      <Main>
       <File_x0020_Name>Test4.KXK</File_x0020_Name>
       <File_x0020_Path>C:\TEST4.KXK</File_x0020_Path>
       <File_x0020_code>1</File_x0020_code>
      </Main>
     </File>
    </FileList>
    Works fine.

  14. #14

    Thread Starter
    Member
    Join Date
    Jun 2002
    Posts
    33
    You are right it works thanks.

  15. #15

    Thread Starter
    Member
    Join Date
    Jun 2002
    Posts
    33
    I know its been a while since my last reply. I wanted to know how would I write to an Xml file like this one if wanted to add a test3.kxk file at the end.

    Code:
    	<File>
    		<Main>
    			<File_x0020_Name>test1.KXK</File_x0020_Name>
    			<File_x0020_Path>C:\TEST1.KXK</File_x0020_Path>
    			<File_x0020_code>1</File_x0020_code>
    		</Main>
    		<Main>
    			<File_x0020_Name>Test2.KXK</File_x0020_Name>
    			<File_x0020_Path>C:\TEST2.KXK</File_x0020_Path>
    			<File_x0020_code>3</File_x0020_code>
    		</Main>
    	</File>

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width