Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here.

How to: Write Object Data to an XML File in Visual Basic

This example writes the object from a class to an XML file using the XmlSerializer class.

This code example defines a class named Book, creates an instance of the class, and uses XML serialization to write the instance to an XML file.

Code similar to this is available as an IntelliSense code snippet. In the code snippet picker, it is located in XML. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).

Public Class Book
    Public Title As String 
    Public Sub New()
    End Sub 
End Class 

Public Sub WriteXML()
    Dim introToVB As New Book
    introToVB.Title = "Intro to Visual Basic" 
    Dim writer As New System.Xml.Serialization.XmlSerializer(GetType(Book))
    Dim file As New System.IO.StreamWriter("c:\IntroToVB.xml")
    writer.Serialize(file, introToVB)
    file.Close()
End Sub

The class must have a public constructor without parameters.

The following conditions may cause an exception:

This example creates a new file, if the file does not already exist. If an application needs to create a file, that application needs Create access for the folder. If the file already exists, the application needs only Write access, a lesser privilege. Where possible, it is more secure to create the file during deployment, and only grant Read access to a single file, rather than Create access for a folder.

Community Additions

ADD
Show:
© 2015 Microsoft