Ad Code

Responsive Advertisement

How To Generate XML File Using Visual Basic




















Suppose you want to save data about books in a library as XML file (with its structure shown above). The data to be read from GUI with controls like TextBox and DataGridView etc.

Imports System.Xml
Imports System.Xml.XmlDocument
Imports System.IO
Imports System.IO.StreamReader

Dim xmlwriter As New XmlTextWriter("library.xml", System.Text.Encoding.UTF8)
xmlwriter.WriteStartDocument(True)
xmlwriter.Formatting = Formatting.Indented
xmlwriter.Indentation = 2
xmlwriter.WriteStartElement("LIBRARY")

xmlwriter.WriteStartElement("BOOK")

xmlwriter.WriteStartElement("ISBN")
xmlwriter.WriteString(tbISBN.Text)
xmlwriter.WriteEndElement()

xmlwriter.WriteStartElement("AUTHOR")
xmlwriter.WriteString(tbAuthor.Text)
xmlwriter.WriteEndElement()

xmlwriter.WriteStartElement("TITLE")
xmlwriter.WriteString(tbTitle.Text)
xmlwriter.WriteEndElement()

For i = 0 To dgvChapter.Rows.Count - 1
xmlwriter.WriteStartElement("CHAPTER")

xmlwriter.WriteStartElement("NUM")
xmlwriter.WriteString(dgvChapter.Rows(i).Cells(0).Value)
xmlwriter.WriteEndElement()

xmlwriter.WriteStartElement("TITLE")
xmlwriter.WriteString(dgvChapter.Rows(i).Cells(1).Value)
xmlwriter.WriteEndElement()

xmlwriter.WriteStartElement("DESCRIPTION")
xmlwriter.WriteString(dgvChapter.Rows(i).Cells(2).Value)
xmlwriter.WriteEndElement()
xmlwriter.WriteEndElement()
Next
'Repeat for more books
....
....
xmlwriter.WriteEndElement() 'end of BOOK TAG

xmlwriter.WriteEndDocument() 'end of LIBRARY TAG

xmlwriter.Close()


Post a Comment

0 Comments