locked
XML Files RRS feed

  • Question

  • I have a XML file containing usernames and passwords. I want to read the data in from that XML file and copy it into an array.

    The code I am using to read the xml file at the moment is:

     Table.ReadXml("Usernames.xml")
     DGV.DataSource = Table

    The array I want to put the data in is called "users"

    Kind Regards

    Tom
    Friday, September 4, 2009 3:36 PM

Answers

  • This will work for you:

    Dim table As New DataTable("Users")
    Dim str As String = File.ReadAllText("YourXmlName.xml")
    table.ReadXmlSchema(New StringReader(str))
    table.ReadXml(New StringReader(str))

    John Grove - TFD Group, Senior Software Engineer, EI Division, http://www.tfdg.com
    • Marked as answer by TomNoble Friday, September 4, 2009 6:30 PM
    Friday, September 4, 2009 6:10 PM
  • I don't want to confuse things here - seen it too many times where someone is trying to learn something, and the OP gets so many different responses, that the OP gets confused more.

    add a datagridview to your form. change the filename to the path for your file

    Imports System.Xml
    Public Class Form1
        Dim Users As New DataTable("Users")
        Dim filename As String = ""
    
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            Me.Size = New Size(500, 500)
           
            
            'create table columns
            Users.Columns.Add("Username", GetType(String))
            Users.Columns.Add("Password", GetType(String))
    
            filename = "C:\Documents and Settings\AVILAJ\Desktop\Test Folder\TomNoble.xml"
    
            DataGridView1.DataSource = Users.DefaultView
                
        End Sub
    
    
        Private Sub btnOpenXML_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOpenXML.Click
            Try
                Users.ReadXmlSchema(filename)
                Users.ReadXml(filename)
            Catch ex As Exception
                MessageBox.Show(Err.Description)
            End Try
        End Sub
    • Marked as answer by TomNoble Friday, September 4, 2009 6:30 PM
    Friday, September 4, 2009 6:25 PM
  • Imports System.IO
    
    Module Module1
    
        Sub Main()
    
            Dim table As New DataTable("Users")
            Dim str As String = File.ReadAllText("1.xml")
            table.ReadXmlSchema(New StringReader(str))
            table.ReadXml(New StringReader(str))
            For Each row As DataRow In table.Rows
                
                Console.WriteLine("Username: {0}", row.Field(Of String)("Username"))
                Console.WriteLine("Password: {0}", row.Field(Of String)("Password"))
                Console.WriteLine("")
            Next
    
            Console.ReadLine()
    
        End Sub
    
    End Module

    //Ouput


    Username: John Smith
    Password: pass

    Username: Roger Smith
    Password: tester

    Username: Test User
    Password: locked

    John Grove - TFD Group, Senior Software Engineer, EI Division, http://www.tfdg.com
    • Marked as answer by TomNoble Friday, September 4, 2009 6:29 PM
    Friday, September 4, 2009 6:28 PM

All replies

  • You don't need DataTable or DataGridView to deserialize an XML file. All you need is an XMLReader. Use that to read your nodes, then write the nodes' text in your array.
    Friday, September 4, 2009 3:54 PM
  • Sorry, your going to have to explain that a little more. This is the first time I have made a proper program in VB.

    Could you please post me a bit of code, that would read in from the file "Usernames.xml", to the array called "users" which is (2, 100).

    Thanks in advance.

    Kind Regards

    Tom
    Friday, September 4, 2009 3:58 PM
  • hi tomnoble ,
    i am new to vb.net, minus well know what an array is, but i hope the following link will provide some information.

    http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/d2c3fd10-e8b4-4ef9-a0b6-e207276cc550
    i live here and this is my reason ... trujade.
    Friday, September 4, 2009 4:15 PM
  • Unfortunately the link the posted doesn't really help.

    What I am trying to do is read in data from a .xml file. Then I want to place that data into an array.

    Through out the program, there will be things done to this, and then at the very end of the program, the old .xml file gets deleted, a new one made, and then this data placed in it.

    Thanks anyway. Helped me understand the way you can add columns etc.

    Kind Regards

    Tom
    Friday, September 4, 2009 4:27 PM
  • Have you tried this:

    Dim table As New DataTable("MyTable")
    Dim str As String = File.ReadAllText("1.xml")
    table.ReadXmlSchema(New StringReader(str))
    table.ReadXml(New StringReader(str))

    Ensure the DataTable.TableName is the name of the "main node", not the DocumentElement.

    //For example in this case the TableName would be "MyTable":

    <?xml version="1.0" standalone="yes"?>
    <DocumentElement>
      <MyTable>
        <ProdID>1</ProdID>
        <Product>Product A</Product>
      </MyTable>
      <MyTable>
        <ProdID>2</ProdID>
        <Product>Product B</Product>
      </MyTable>
      <MyTable>
        <ProdID>3</ProdID>
        <Product>Product C</Product>
      </MyTable>
      <MyTable>
        <ProdID>4</ProdID>
        <Product>Product D</Product>
      </MyTable>
    </DocumentElement>
                
               
    John Grove - TFD Group, Senior Software Engineer, EI Division, http://www.tfdg.com
    • Edited by JohnGrove Friday, September 4, 2009 6:06 PM
    Friday, September 4, 2009 5:19 PM
  • Here's a code snippet that gives a general example of what I meant. Of course without an example of your XML file I can't know the exact structure of your file, so this is all wild guesses, but it gives a pretty good idea.

        Public Class Login
            Public UserName As String
            Public Password As String
        End Class
    
        Private Sub DeserializeXMLFile()
            Using myReader As Xml.XmlReader = Xml.XmlReader.Create("MyXMLFile.xml")
                Dim myLoginList As New List(Of Login)
                While myReader.Read
                    If myReader.Name = "UserName" Then
                        myLoginList.Add(New Login)
                        myLoginList.Last.UserName = myReader.Value
                    ElseIf myReader.Name = "Password" Then
                        myLoginList.Last.Password = myReader.Value
                    End If
                End While
            End Using
        End Sub
    PS This code has very little error handling, if the first node is a password for example, it will crash. Don't use it as is.
    Friday, September 4, 2009 5:29 PM
  • Tom,
    Don't be helpless. And don't trivialize the help you are receiving from other forum contributors who do this on a volunteer basis. It is very disparaging to try to help someone who doesn't take initiative and quickly dismisses the help given.

    What you could have done if you really wanted assistence is display a sample of this "Xml file" so others can see its schema. You say you want the Xml in an array, then your example shows you attempting to put it in a DataTable. Which is it brother?

    The more articulate you can hone your question, the more precise an attempted answer will become.

    Please


    John Grove - TFD Group, Senior Software Engineer, EI Division, http://www.tfdg.com
    • Edited by JohnGrove Friday, September 4, 2009 6:05 PM
    Friday, September 4, 2009 5:37 PM
  • So would something like this work?

    Global Variable

    Public Users(2,100) As String


    Private Sub ReadFile()

    Counter=1
    Using myReader As Xml.XmlReader = Xml.XmlReader.Read('Directory of file goes here')
    While myReader.Read
       MyReader.Name = Users(1, Counter)
       MyReader.Name = Users(2, Counter)
       Counter +=1
    End While

    All I need to be able to do, is read in the below file, and as it reads it in, put it into the correct place in the array "users" which has 2 columns and 100 rows. Column 1 is the username, 2 is the password.

    Once it is in there then I can do everything in the program.

    At the end of the prorgam I should just be able to convert the code into something that writes back into the .xml file.

    I really have no idea what I am doing so as much help as possible is appreciated.

    Here is a copy of the xml file:

    BODY{font:x-small 'Verdana';margin-right:1.5em} .c{cursor:hand} .b{color:red;font-family:'Courier New';font-weight:bold;text-decoration:none} .e{margin-left:1em;text-indent:-1em;margin-right:1em} .k{margin-left:1em;text-indent:-1em;margin-right:1em} .t{color:#990000} .xt{color:#990099} .ns{color:red} .dt{color:green} .m{color:blue} .tx{font-weight:bold} .db{text-indent:0px;margin-left:1em;margin-top:0px;margin-bottom:0px;padding-left:.3em;border-left:1px solid #CCCCCC;font:small Courier} .di{font:small Courier} .d{color:blue} .pi{color:blue} .cb{text-indent:0px;margin-left:1em;margin-top:0px;margin-bottom:0px;padding-left:.3em;font:small Courier;color:#888888} .ci{font:small Courier;color:#888888} PRE{margin:0px;display:inline}
      <? xml version="1.0" standalone="yes" ?>
    - < DocumentElement >
    - <Users >
      <Username > John Smith </Username >
      <Password >pass </Password >
      </Users >
    - <Users >
    <Username > Roger </Username >
    <Password >pass </Password >
      </Users >
      </ DocumentElement >

    Kind Regards

    Tom
    Friday, September 4, 2009 5:43 PM

  • Would it work?  Run the code and you tell us.  That is called debugging.

    Mark the best replies as answers. "Fooling computers since 1971."
    Friday, September 4, 2009 5:47 PM
  • Sorry Tom, I skipped over the part where you mention this is your first VB program. I assumed you had a bit more of a background when I answered.

    At the top of this page you'll find a "Learn" link, from there you can find a "VB.Net" link that will bring you a wealth of introduction level tutorials on how to make your first programs in VB.Net. I suggest you start with something a little more basic then serialization/deserialization to cut your teeth.

    Also, don't use arrays. List(Of YourType) is the way the cool kids do it nowadays.
    Friday, September 4, 2009 5:47 PM
  • One thing that will help you learn also is in the line where you have XMLReader.Read, place your cursor somewhere within the word XMLReader. Then hit F1. That will take you to the MSDN page for that item.  There you can read all about that item - what types of aparameters, overloads, etc

    You will be able to read all kinds of info there. It will work for most things you type in the code editor - DataTypes (String, etc), Controls (DataGridView, etc)...
    Friday, September 4, 2009 5:53 PM
  • I would like to start on something a little bit easier, but I am a student who has been set the challenge of: "Reading data from a .xml file into an array for searching. The user must be able to type in the name they want to find)

    I have been trying to get the xml to array bit working for about 2 months now, and just can't find anything that I understand or can adapt to my program.

    Apologies if you think I am just being a little bit thick, or dismissing your answers, but I really need to get something that I understand and can implement to get a working solution.

    If I were to do this from a text file, I would be fine. I have 2 text file solutions.

    I have programmed in Pascal before, but this is my first VDE.

    Kind Regards

    Tom
    Friday, September 4, 2009 5:55 PM
  • Have you tried this:

    Dim table As New DataTable("MyTable")
    Dim str As String = File.ReadAllText("1.xml")
    table.ReadXmlSchema(New StringReader(str))
    table.ReadXml(New StringReader(str))

    Ensure the DataTable.TableName is the name of the "main node", not the DocumentElement.

    //For example in this case the TableName would be "MyTable":

    <?xml version="1.0" standalone="yes"?>
    <DocumentElement>
      <MyTable>
        <ProdID>1</ProdID>
        <Product>Product A</Product>
      </MyTable>
      <MyTable>
        <ProdID>2</ProdID>
        <Product>Product B</Product>
      </MyTable>
      <MyTable>
        <ProdID>3</ProdID>
        <Product>Product C</Product>
      </MyTable>
      <MyTable>
        <ProdID>4</ProdID>
        <Product>Product D</Product>
      </MyTable>
    </DocumentElement>
                
               
    John Grove - TFD Group, Senior Software Engineer, EI Division, http://www.tfdg.com

    This worked just fine for me...

    Again, what does this Xml look like?
    John Grove - TFD Group, Senior Software Engineer, EI Division, http://www.tfdg.com
    Friday, September 4, 2009 6:06 PM
  • appologies, didnt see the request for Xml file. Here is the file I have to read in:

    <?xml version="1.0" standalone="yes"?>
    <DocumentElement>
      <Users>
        <Username>John Smith</Username>
        <Password>pass</Password>
      </Users>
      <Users>
        <Username>Roger Smith</Username>
        <Password>tester</Password>
      </Users>
    <Users>
        <Username>Test User</Username>
        <Password>locked</Password>
      </Users>
    </DocumentElement>
    Friday, September 4, 2009 6:09 PM
  • This will work for you:

    Dim table As New DataTable("Users")
    Dim str As String = File.ReadAllText("YourXmlName.xml")
    table.ReadXmlSchema(New StringReader(str))
    table.ReadXml(New StringReader(str))

    John Grove - TFD Group, Senior Software Engineer, EI Division, http://www.tfdg.com
    • Marked as answer by TomNoble Friday, September 4, 2009 6:30 PM
    Friday, September 4, 2009 6:10 PM
  • Make sure you add this imports statement

    Imports System.IO
    John Grove - TFD Group, Senior Software Engineer, EI Division, http://www.tfdg.com
    Friday, September 4, 2009 6:12 PM
  • Make sure you add this imports statement

    Imports System.IO
    John Grove - TFD Group, Senior Software Engineer, EI Division, http://www.tfdg.com



    Can you post a complete module1.vb file?

    Mark the best replies as answers. "Fooling computers since 1971."
    Friday, September 4, 2009 6:16 PM
  • Ok, I have that bit working now.

    The final question I have is, if I want to look at say the third element in the data table (like you would do in an array "Array_Name(Position)"), how do you do it?

    I want to make lbl_result.text= Table(Position in table)

    Thanks so much for your help everyone. John this is a brillaint solution.

    Kind Regards

    Tom
    Friday, September 4, 2009 6:16 PM
  • Another possible solution is to use the XMLDocument class. This is an oversimplified example of how to use it.

        Private Sub DeserializeXMLFile()
            Dim myLoginList(2, 100) As String
            Dim myCounter As Integer = 0
            Dim myXMLDocument As New Xml.XmlDocument
            myXMLDocument.Load("UserNames.xml")
    
            'Find the first Users node. It's the child of the second child of the root node.
            Dim myNode = myXMLDocument.ChildNodes(1).ChildNodes(0)
    
            'Iterate through all the "Users" nodes.
            While myNode IsNot Nothing
    
                'The "Username" should be the first child node.
                myLoginList(0, myCounter) = myNode.ChildNodes(0).ChildNodes(0).Value
                'The "Password" is the 2nd child node.
                myLoginList(1, myCounter) = myNode.ChildNodes(1).ChildNodes(0).Value
    
                'Increment counter and fetch next Users node.
                myCounter += 1
                myNode = myNode.NextSibling
            End While
        End Sub
    Friday, September 4, 2009 6:17 PM
  • Thanks Billy Bob, that also works for my program.

    Both these results are brilliant. Thanks so much.

    Kind Regards

    Tom
    Friday, September 4, 2009 6:23 PM
  • I don't want to confuse things here - seen it too many times where someone is trying to learn something, and the OP gets so many different responses, that the OP gets confused more.

    add a datagridview to your form. change the filename to the path for your file

    Imports System.Xml
    Public Class Form1
        Dim Users As New DataTable("Users")
        Dim filename As String = ""
    
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            Me.Size = New Size(500, 500)
           
            
            'create table columns
            Users.Columns.Add("Username", GetType(String))
            Users.Columns.Add("Password", GetType(String))
    
            filename = "C:\Documents and Settings\AVILAJ\Desktop\Test Folder\TomNoble.xml"
    
            DataGridView1.DataSource = Users.DefaultView
                
        End Sub
    
    
        Private Sub btnOpenXML_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOpenXML.Click
            Try
                Users.ReadXmlSchema(filename)
                Users.ReadXml(filename)
            Catch ex As Exception
                MessageBox.Show(Err.Description)
            End Try
        End Sub
    • Marked as answer by TomNoble Friday, September 4, 2009 6:30 PM
    Friday, September 4, 2009 6:25 PM
  •     Private Sub DeserializeXMLFile()
            Dim myLoginList(2, 100) As String
            Dim myCounter As Integer = 0
            Dim myXMLDocument As New Xml.XmlDocument
            myXMLDocument.Load("UserNames.xml")
    
            'Find the first Users node. It's the child of the second child of the root node.
            Dim myNode = myXMLDocument.ChildNodes(1).ChildNodes(0)
    
            'Iterate through all the "Users" nodes.
            While myNode IsNot Nothing
    
                'The "Username" should be the first child node.
                myLoginList(0, myCounter) = myNode.ChildNodes(0).ChildNodes(0).Value
                'The "Password" is the 2nd child node.
                myLoginList(1, myCounter) = myNode.ChildNodes(1).ChildNodes(0).Value
    
                'Increment counter and fetch next Users node.
                myCounter += 1
                myNode = myNode.NextSibling
            End While
        End Sub
    
    or

    Import System.IO
    
    Dim table As New DataTable("Users")
    Dim str As String = File.ReadAllText("YourXmlName.xml")
    table.ReadXmlSchema(New StringReader(str))
    table.ReadXml(New StringReader(str))
    • Marked as answer by TomNoble Friday, September 4, 2009 6:26 PM
    • Unmarked as answer by TomNoble Friday, September 4, 2009 6:29 PM
    Friday, September 4, 2009 6:26 PM
  • Imports System.IO
    
    Module Module1
    
        Sub Main()
    
            Dim table As New DataTable("Users")
            Dim str As String = File.ReadAllText("1.xml")
            table.ReadXmlSchema(New StringReader(str))
            table.ReadXml(New StringReader(str))
            For Each row As DataRow In table.Rows
                
                Console.WriteLine("Username: {0}", row.Field(Of String)("Username"))
                Console.WriteLine("Password: {0}", row.Field(Of String)("Password"))
                Console.WriteLine("")
            Next
    
            Console.ReadLine()
    
        End Sub
    
    End Module

    //Ouput


    Username: John Smith
    Password: pass

    Username: Roger Smith
    Password: tester

    Username: Test User
    Password: locked

    John Grove - TFD Group, Senior Software Engineer, EI Division, http://www.tfdg.com
    • Marked as answer by TomNoble Friday, September 4, 2009 6:29 PM
    Friday, September 4, 2009 6:28 PM
  • I don't want to confuse things here - seen it too many times where someone is trying to learn something, and the OP gets so many different responses, that the OP gets confused more.
    Nonsense! This simply comes to show us how rich the .Net platform is. The more solutions the better. We can then pick and choose which one applies best to each scenario.
    • Proposed as answer by JohnGrove Friday, September 4, 2009 6:30 PM
    Friday, September 4, 2009 6:29 PM
  • Well said Billy
    John Grove - TFD Group, Senior Software Engineer, EI Division, http://www.tfdg.com
    Friday, September 4, 2009 6:30 PM
  • From a learners prospective, the more answers there are the better.

    Thanks all so much

    Friday, September 4, 2009 6:31 PM
  • Good job Tom.....
    John Grove - TFD Group, Senior Software Engineer, EI Division, http://www.tfdg.com
    Friday, September 4, 2009 6:40 PM
  • Thanks Billy...just didn't want to confuse things more. I've seen it numerous times. And I've been responsible for it myself :(

    And Tom mentioned reading it into an array - don't see the need for that since a datatable is essentially a 2 (or more) dimensional array. Once it is in the datatable, can utilize the data just as easily - maybe easier using things like queries or DataViews to filter, sort, etc.


    @Tom
    The datagridview was just a way to display the data. You don't have to have that - just depends on what you are going to do with the data
    Friday, September 4, 2009 6:47 PM