Monday, October 17, 2011

Create XML File from code behind in VB.Net

For generate XML File from code behind in vb.net follow the below steps :

First Import name space
Imports System.Xml 
then you can write this simple function
Public Sub CreateXML( )



        Dim _FilePath As String = Application.StartupPath + "\MainXML.xml"
        If Not File.Exists(_FilePath) Then
            '' Create new xml File
            Dim writer As New XmlTextWriter(_FilePath, Nothing)
            writer.WriteStartElement("XMLInfo")
            writer.WriteEndElement()
            writer.Close()
        End If

        '' If File Exist then appand data

        If File.Exists(_FilePath) Then
            Dim objXML As New XmlDocument
            Dim NewItem As String = " "
            objXML.Load(_FilePath)
            Dim docFrag As XmlDocumentFragment = objXML.CreateDocumentFragment()
            docFrag.InnerXml = NewItem
           Dim root As XmlNode = objXML.DocumentElement
            root.AppendChild(docFrag)
            objXML.Save(_FilePath)
        End If
    End Sub

No comments:

Post a Comment