Monday, March 12, 2012

Reading and Writing XML in VB.net



how to store the data on listboxt and when you open the application, the data is still there , I searched on google how to do it, it turns out that using xmlrader and write it back use xmltextrwiter, the original code is not belongs to me,but I'll explain how it works with vb.net .

the code below represent how to read each of the element of xml, and write it into listbox.

Code:
Dim XMLReader As Xml.XmlReader
 XMLReader =New Xml.XmlTextReader("text.xml")'you also can change the directory from xml
   While XMLReader.Read                      'ex. ("Data\xmldata text.xml")
     Select Case XMLReader.NodeType          'selecet the node (file) from text.xml
         Case Xml.XmlNodeType.Element
            If XMLReader.AttributeCount > 0 Then 'xmlraeder will start from zero
              While XMLReader.MoveToNextAttribute
                 If XMLReader.Name = "File" Then
                    ListBox1.Items.Add(XMLReader.Value)'looping and add each of the elem                                                       'ent into listbox
                 Else
                 End If
              End While
            End If
     End Select
   End While
XMLReader.Close()

and how write it back and save into xml file, you can use the code below.

Code:
 Dim XMLobj As Xml.XmlTextWriter
 Dim ue As New System.[Text].UnicodeEncoding    'unicode 
 XMLobj = New Xml.XmlTextWriter("text.xml", ue) 'rewrite text.xml
 XMLobj.Formatting = Xml.Formatting.Indented
 XMLobj.Indentation = 3
 XMLobj.WriteStartDocument()   'xml will be declared with the xml version="1.0"
 XMLobj.WriteStartElement("List") ' write the node (file)
 Dim i As Integer
  For i = 0 To ListBox1.Items.Count - 1 'looping and  XmlTextWriter will be begun from listbox.value(0)        
     XMLobj.WriteStartElement("Text")   'from text.xml
     Dim temp As String = ""            
     ListBox1.SetSelected(i, True)
     temp = ListBox1.SelectedItem
     XMLobj.WriteAttributeString("File", temp)
     XMLobj.WriteEndElement()
  Next
 XMLobj.WriteEndElement()
 XMLobj.Close() 

besides xml you can also use my.setting  as a dynamic storage you can find it in project properties


My.Setting
to read and display
Code:
Me.TextBox1.Text = My.Settings.IPAddress
and rewrite
My.Settings.IPAddress = Me.TextBox1.Text 


sourcecode

1 comment:

  1. Oh! This info I was looking for! thanks a lot for the prompts and video! Find more here proofreading-services.org/professional.php see you.

    ReplyDelete