[VB.NET] Read - Write XML


Description
     this is simple example to read and write XML for VB.NET. if you have a better method please comment it. the best and simple way i will include in article. thanks

How To

Write XML - In Module :

Imports System.IO
Imports System.Text

Public Sub saveSettingXML()
        Dim savepath As String = My.Application.Info.DirectoryPath

        ' Create a string builder and write the user input from the textbox to it. 
        Dim XML As StringBuilder = New StringBuilder()
        XML.AppendLine("<?xml version=""1.0"" encoding=""UTF-8""?>")
        XML.AppendLine("<data>")
        XML.AppendLine("<person>" & "Mahendra" & "</person>" & vbCrLf)
        XML.AppendLine("<position>" & "IT Engineer" & "</position>" & vbCrLf)
        XML.AppendLine("</data>")

        ' Write the stream cotnents to a new file named "setting.xml" 
        Using outfile As New StreamWriter(savepath & "\setting.xml")
            outfile.Write(XML.ToString())
        End Using
    End Sub

and to use just call : saveSettingXML()

the XML text will be create like this : 
<?xml version="1.0" encoding="UTF-8" ?>
    - <data>
            <person>Mahendra</person>
            <position>IT Engineer</position>
      </data>



To Read XML above :

'always check existing file first !
 If System.IO.File.Exists(My.Application.Info.DirectoryPath & "\setting.xml") Then
            'if file xml exist read the setting
            Dim xml = XDocument.Load(My.Application.Info.DirectoryPath & "\setting.xml")
            frmInvoiceStandart.txtPersonName.Text = xml.<data>.<person>.Value
            frmInvoiceStandart.txtPersonPosition.Text = xml.<data>.<position>.Value
 Else
           'if not exist just create the setting or bla bla bla .....
End If

horayyyy :D

Post a Comment

Harap gunakan bahasa yang baik dan sopan, terima kasih