Click here to Skip to main content
15,039,244 members
Articles / Programming Languages / XML
Tip/Trick
Posted 8 Feb 2014

Tagged as

Stats

78.9K views
10 bookmarked

How to Save a Class Instance to an XML File

Rate me:
Please Sign up or sign in to vote.
4.20/5 (3 votes)
8 Feb 2014CPOL
Easily save an object as XML

eXceedingly siMpLe

Not too many things are easier than this. Once you have a class (you do have class, don't you? I mean, a class?), simply pass an instance of it (with values assigned to its members) to a method like this:

C#
private void SaveToXML(Platypus platypup)
{
    System.Xml.Serialization.XmlSerializer writer =
        new System.Xml.Serialization.XmlSerializer(typeof(Platypus));

    StreamWriter file = new StreamWriter("Platypi.xml");
    writer.Serialize(file, platypup);
    file.Close();
}

The only thing you'll need to change in the code above is the name of the class type (yours is probably not "Platypus") in two places. You might want to change the variable name, too (from "platypup") and the name of the XML file (from "Platypi.xml").

After calling this method, you will be overjoyed (beside yourself with glee, even, perhaps) to discover something like the following file on disk:

XML
<platypus xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <id>42</id>
  <nickname>Snoop Platypuppy Pup</nickname>
  <seriousname>Platypup</seriousname>
  <birthyear>1835</birthyear>
  <feed>Purina Platypus Chow</feed>
  <language>Plattdeutsch</language>
  <favoritemovie>Naplatypus Dynamite</favoritemovie>
</platypus>

If you find this tip useful, consider adopting an exceedingly neutral stand towards ambivalence.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

B. Clay Shannon
Founder Across Time & Space
United States United States
I am in the process of morphing from a software developer into a portrayer of Mark Twain. My monologue (or one-man play, entitled "The Adventures of Mark Twain: As Told By Himself" and set in 1896) features Twain giving an overview of his life up till then. The performance includes the relating of interesting experiences and humorous anecdotes from Twain's boyhood and youth, his time as a riverboat pilot, his wild and woolly adventures in the Territory of Nevada and California, and experiences as a writer and world traveler, including recollections of meetings with many of the famous and powerful of the 19th century - royalty, business magnates, fellow authors, as well as intimate glimpses into his home life (his parents, siblings, wife, and children).

Peripatetic and picaresque, I have lived in eight states; specifically, besides my native California (where I was born and where I now again reside) in chronological order: New York, Montana, Alaska, Oklahoma, Wisconsin, Idaho, and Missouri.

I am also a writer of both fiction (for which I use a nom de plume, "Blackbird Crow Raven", as a nod to my Native American heritage - I am "½ Cowboy, ½ Indian") and nonfiction, including a two-volume social and cultural history of the U.S. which covers important events from 1620-2006: http://www.lulu.com/spotlight/blackbirdcraven

Comments and Discussions

 
SuggestionThe function can be more generally Pin
Mr. xieguigang 谢桂纲8-Feb-14 19:16
professionalMr. xieguigang 谢桂纲8-Feb-14 19:16 
you can using a Generic function to makes the operation more generally like i did:
each of the project in my coding job, i write a generic extension function to serialization a class object like this Big Grin | :-D :

    ''' <summary>
    ''' 将一个类对象序列化为XML文档
    ''' </summary>
    ''' <typeparam name="T"></typeparam>
    ''' <param name="e"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    <Extension> Public Function GetXml(Of T As Class)(e As T) As String
        Dim sBuilder As StringBuilder = New StringBuilder(1024)
        Using Stream As New System.IO.StringWriter(sb:=sBuilder)
#If DEBUG Then
            Try
                Call (New System.Xml.Serialization.XmlSerializer(GetType(T))).Serialize(Stream, e)
            Catch ex As Exception
                FileIO.FileSystem.WriteAllText(My.Computer.FileSystem.SpecialDirectories.Temp & "/error.log", ex.ToString & vbCrLf & vbCrLf, append:=True)
                Throw
            End Try
#Else
            Call (New System.Xml.Serialization.XmlSerializer(GetType(T))).Serialize(Stream, e)
#End If
            Return sBuilder.ToString
        End Using
    End Function


 ''' <summary>
    ''' 
    ''' </summary>
    ''' <typeparam name="T"></typeparam>
    ''' <param name="Xml">XML文件的文件路径</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    <Extension> Public Function LoadXml(Of T As Class)(Xml As String) As T
        Dim FileContent As String = FileIO.FileSystem.ReadAllText(file:=Xml)
        Using Stream As New System.IO.StringReader(s:=FileContent)
#If DEBUG Then
            Try
                Dim Type = GetType(T)
                Dim Data = New System.Xml.Serialization.XmlSerializer(Type).Deserialize(Stream)
                Return DirectCast(Data, T)
            Catch ex As Exception
                FileIO.FileSystem.WriteAllText(My.Computer.FileSystem.SpecialDirectories.Temp & "/error.log", ex.ToString & vbCrLf & vbCrLf, append:=True)
                Throw
            End Try
#Else
            Return DirectCast(New System.Xml.Serialization.XmlSerializer(GetType(T)).Deserialize(Stream), T)
#End If
        End Using
    End Function 



''' <summary>
 ''' 将目标文本字符串写入到一个指定路径的文件之中,但是不会在文件末尾追加新的数据
 ''' </summary>
 ''' <param name="Path"></param>
 ''' <param name="Text"></param>
 ''' <param name="Encoding"></param>
 ''' <returns></returns>
 ''' <remarks></remarks>
 <Extension> Public Function Save(Text As String, Path As String, Optional Encoding As System.Text.Encoding = Nothing) As Boolean
     If String.IsNullOrEmpty(Path) Then Return False
     If Encoding Is Nothing Then Encoding = System.Text.Encoding.UTF8
     Dim Dir = FileIO.FileSystem.GetParentPath(Path)
     Call FileIO.FileSystem.CreateDirectory(Dir)
     Call FileIO.FileSystem.WriteAllText(Path, Text, append:=False, encoding:=Encoding)
     Return True
 End Function


then, we can save the data in the class more easy:

save data:

call ObjectInstance.GetXml.Save(FilePath)

load data:

Dim ObjectInstance = FilePath.LoadXml(Of YourClassType)

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.